after DIMES US5
authorA.M. Thurnherr <ant@ldeo.columbia.edu>
Thu, 21 Nov 2013 09:07:17 -0500
changeset 13 2788bf1bf1de
parent 12 2adcd220b9b4
child 14 fea65697bc7b
after DIMES US5
LADCP_w
LWplot_BR
LWplot_CAE
LWplot_Sv
LWplot_TL
LWplot_corr
LWplot_prof
LWplot_prof_2beam
LWplot_spec
Sv.cpt
bottom_tracking.pl
defaults.pl
edit_data.pl
time_lag.pl
time_series.pl
w.cpt
--- a/LADCP_w	Sat Mar 23 13:45:31 2013 +0000
+++ b/LADCP_w	Thu Nov 21 09:07:17 2013 -0500
@@ -2,9 +2,9 @@
 #======================================================================
 #                    L A D C P _ W 
 #                    doc: Fri Dec 17 18:11:13 2010
-#                    dlm: Sat Mar 23 13:44:57 2013
+#                    dlm: Thu Sep  5 16:23:16 2013
 #                    (c) 2010 A.M. Thurnherr
-#                    uE-Info: 126 0 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 495 0 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # TODO:
@@ -123,6 +123,19 @@
 #	Feb 13, 2013: - BUG: CTD_neg_press_offset did not work for CTD time series with -ve starting depth
 #	Mar 23, 2013: - cosmetics
 #				  - HG COMMIT
+#	Apr 22, 2013: - removed opt_? variable aliases
+#	May  8, 2013: - replaced default run label (default to profiles) to make more readable directory structure
+#	May 14, 2013: - opt_m => w_max_lim
+#				  - BUG: time-series output had two messed-up fields
+#	May 15, 2013: - added w12 and w34 (2-beam solutions) to profile output
+#	May 16, 2013: - added CTD_w_tt to time-series & all-sample outputs
+#			      - -a => -d (CTD depth offset)
+#				  - implemented pressure-sensor acceleration correction (-a)
+#				  - added re-gridding of full profile after ping-coherent error removal
+#	Jun  5, 2013: - renamed $discard_velocities_from_beam to $bad_beam
+#				  - BUG: $bad_beam did not discard BT_VELOCITY data
+#	Jun  6, 2013: - BUG: error message had -a instead of -d
+#	Sep  5, 2013: - BUG: w12/w34 do not work for earth-coordinate data, of course
 
 # CTD REQUIREMENTS
 #	- elapsed		elapsed seconds; see note below
@@ -132,6 +145,11 @@
 #	- temp			OPTIONAL; used for backscatter calculation (i.e. not very important)
 #	- %lat/%lon		OPTIONAL
 
+# 2-BEAM SOLUTIONS
+#	- for beam-coordinate data, two separate two-beam solutions (w12 & w34) are calculated
+#	- discrepancies can be indicative of package wake effects (e.g. MIXET data)
+#	- for earth-coordinate data, w12 and w34 are simply copies of w
+
 # NUMERICAL OPTIONS
 #	- the first option in the list cannot be numerical!
 #	- if need be, use -v 1 as a dummy option
@@ -155,8 +173,10 @@
 #	- as a result, a profile only starts with elapsed==0 if the CTD
 #	  is turned on when the LADCP is already in the water
 
-# OUTPUT NOTES
-#	- residuals are calculated with respect to down-/upcast medians in binned profiles
+# BINNED-PROFILE OUTPUT NOTES
+#	- residuals are calculated with respect to down-/upcast medians
+#	- w12 and w34 2-beam solutions are reported without considering
+#	  -k (min samples)
 #	- equivalence, assuming -o 10:
 #		1) 004DL.prof dc_w depth
 #		2) bindata -Sdowncast:1 -Fw.median,depth -n 20 depth 10 004DL.w
@@ -195,19 +215,19 @@
 @ARGS = @ARGV;														# save opts & arguments
 
 $antsParseHeader = 0;
-&antsUsage('3:4a:b:c:e:g:h:i:k:m:n:o:qs:t:uv:w:x:',1,
+&antsUsage('3:4a:b:c:e:g:h:i:k:m:n:o:p:qs:t:uv:w:x:',1,
 	'[-v)erbosity <level[1]>]',
 	'[-q)uick (no single-ping denoising)]',
-    '[require -4)-beam solutions]',
+    '[require -4)-beam solutions] [apply beamvel-m)ask <file> if it exists]',
+	'[valid LADCP -b)ins <bin[2],bin[*]>',
 	'[-c)orrelation <min[70]>] [-t)ilt <max[10deg]> [-e)rr-vel <max[0.1m/s]>]',
 	'[-h water <depth>]',
 	'[max LADCP time-series -g)ap <length[60s]>]',
-	'[-m)ax vertical <velocity[1m/s]>',
-	'[-a)djust CTD depth <by[0m]>]',
+	'[offset CTD -d)epth <by[0m]>]',
 	'[-i)nitial CTD time offset <guestimate> [-u)se as final]]',
-	'[calculate -n) <lags,lags[10,100]>] [lag -w)indow <sz,sz[240s,20s]>]',
+	'[calculate -n) <lags,lags[10,100]>] [lag -w)indow <sz,sz[240s,20s]>] [lag-p)iece <CTD_elapsed_min|+[,...]>]',
 	'[require top-3) lags to account for <frac[0.6]> of all]',
-	'[valid LADCP -b)ins <bin[2],bin[*]>',
+	'[pressure-sensor -a)cceleration correction <residual/CTD_w_tt>]',
 	'[-o)utput bin <resolution[10m]>] [-k) require <min[20]> samples]',
 	'[e-x)ecute <perl-expr>]',
 	'<station-id> [run-label]');
@@ -215,24 +235,42 @@
 &antsUsageError() if ($opt_u && !defined($opt_i));
 
 &antsCardOpt(\$opt_s,0);											# skip # initial ensembles
+$opt_p = '+' unless defined($opt_p);								# separate uc/dc time lagging
+
+&antsFloatOpt(\$opt_a,1);											# pressure acceleration correction
 
 $STN = &antsCardArg();												# station id
 if (@ARGV) {														# run label
 	$RUN = $ARGV[0];
 	shift;
 } else {
-	$RUN = 'default';
+	$RUN = 'profiles';
 }
 
 #-----------------------------
 # Handle Processing Parameters
 #-----------------------------
 
-require "$WCALC/defaults.pl";										# load default/option parameters
-require "$processing_param_file";									# load processing parameters
-eval($opt_x) if defined($opt_x);									# eval cmd-line expression to override anything
+require "$WCALC/defaults.pl";											# load default/option parameters
+require "$processing_param_file";										# load processing parameters
+eval($opt_x) if defined($opt_x);										# eval cmd-line expression to override anything
 
-croak("$0: \$out_basename undefined\n")								# all plotting routines use this
+$RDI_Coords::minValidVels = 4 if ($opt_4);								# decode cmd-line arguments
+($LADCP_firstBin,$LADCP_lastBin) = split(',',$opt_b);
+	croak("$0: cannot decode -b $opt_b\n")
+    	unless (numberp($LADCP_firstBin) &&
+        	    ($LADCP_lastBin eq '*' || numberp($LADCP_lastBin)));
+@number_of_timelag_windows = split(',',$opt_n);
+	croak("$0: cannot decode -n $opt_n\n")
+		unless numberp($number_of_timelag_windows[0]) && numberp($number_of_timelag_windows[1]);
+@length_of_timelag_windows = split(',',$opt_w);
+	croak("$0: cannot decode -w $opt_w\n")
+		unless numberp($length_of_timelag_windows[0]) && numberp($length_of_timelag_windows[1]);
+
+
+
+
+croak("$0: \$out_basename undefined\n")									# all plotting routines use this
 	unless defined($out_basename);
 &antsAddParams('out_basename',$out_basename);
 &antsAddParams('run_label',$RUN);
@@ -259,14 +297,14 @@
 sub progress(@)
 {
 	printf(LOGF @_) if defined($out_log);
-	printf(STDERR @_) if ($verbosity_level > 1);
+	printf(STDERR @_) if ($opt_v > 1);
 }
 
 sub info(@)
 {
 	printf(LOGF "\t",@_) if defined($out_log);
-	print(STDERR ($verbosity_level > 1) ? "\t" : "$LADCP_file: ");
-	printf(STDERR @_)  if ($verbosity_level > 0);
+	print(STDERR ($opt_v > 1) ? "\t" : "$LADCP_file: ");
+	printf(STDERR @_)  if ($opt_v > 0);
 }
 	
 sub warning(@)
@@ -278,15 +316,15 @@
 		printf(LOGF @msg);
 		print(LOGF "\n");
 	}
-	return if ($verbosity_level == 0);
-	print(STDERR "\n") if ($verbosity_level > 1);
+	return if ($opt_v == 0);
+	print(STDERR "\n") if ($opt_v > 1);
 	print(STDERR "WARNING (level $lvl): ");
 	printf(STDERR @msg);
-	print(STDERR "\n") if ($verbosity_level > 1);
+	print(STDERR "\n") if ($opt_v > 1);
 }
 
 sub debugmsg(@)
-{ printf(STDERR @_) if ($verbosity_level > 2); }
+{ printf(STDERR @_) if ($opt_v > 2); }
 
 #----------------
 # Read LADCP data
@@ -329,32 +367,62 @@
 
 #------------------------------------------------------------
 # Edit beam-velocity data
+#	0) beam-vel mask on -m
 #	1) correlation threshold
 #------------------------------------------------------------
 
 if ($LADCP{BEAM_COORDINATES}) {
 	progress("Editing beam-velocity data...\n");
+	
+	if (defined($opt_m) && -r $opt_m) {
+		progress("\tmasking beam velocities according to $opt_m:");
+
+		my($nee) = 0;
+		open(BVM,$opt_m) || die("$opt_m: $!\n");
+		while (<BVM>) {
+			s/#.*//;
+			s/^\s*$//;
+			next if ($_ eq '');
+			my($fe,$te,$db) = split;
+			die("$opt_m: cannot decode $_\n")
+				unless (numberp($fe) && numberp($te) && $te>=$fe && $db>=1 && $db<=4);
+			die("$0: assertion failed")
+				unless ($LADCP{ENSEMBLE}[$fe-1]->{NUMBER} == $fe &&
+						$LADCP{ENSEMBLE}[$te-1]->{NUMBER} == $te);
+			for (my($ens)=$fe-1; $ens<=$te-1; $ens++) {
+				$nee++;
+				for (my($bin)=0; $bin<$LADCP{N_BINS}; $bin++) {
+					undef($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][$db-1]);
+				}
+			}
+		}
+		print(STDERR " $nee ensembles edited\n");
+		close(BVM);
+	}
+
 	$nvv = $cte = 0;
 	for ($ens=0; $ens<=$#{$LADCP{ENSEMBLE}}; $ens++) {
 		correctAttitude($ens,$pitch_bias,$roll_bias,$heading_bias);
 		$nvv += countValidBeamVels($ens);
-		$cte += editCorr($ens,$min_correlation);
-#		$pte += editTilt($ens,$max_tilt);
+		$cte += editCorr($ens,$opt_c);
+#		$pte += editTilt($ens,$opt_t);
 	}
 	croak("$LADCP_file: no valid data\n") unless ($nvv > 0);
-	progress("\tcorrelation threshold (-c %d counts): %d velocites removed (%d%% of total)\n",$min_correlation,$cte,round(100*$cte/$nvv));
-#	progress("\tattitude threshold (-t %d deg): %d velocites removed (%d%% of total)\n",$max_tilt,$pte,round(100*$pte/$nvv));
+	progress("\tcorrelation threshold (-c %d counts): %d velocites removed (%d%% of total)\n",$opt_c,$cte,round(100*$cte/$nvv));
+#	progress("\tattitude threshold (-t %d deg): %d velocites removed (%d%% of total)\n",$opt_t,$pte,round(100*$pte/$nvv));
 } else {
 	progress("Editing velocity data...\n");
+	croak("$LADCP_file: cannot apply beamvel-mask $opt_m to earth-coordinate data\n")
+		if defined($opt_m);
 	$nvv = $cte = 0;
 	for ($ens=0; $ens<=$#{$LADCP{ENSEMBLE}}; $ens++) {
 		$nvv += countValidBeamVels($ens);
-		$cte += editCorr_Earthcoords($ens,$min_correlation);
-#		$pte += editTilt($ens,$max_tilt);
+		$cte += editCorr_Earthcoords($ens,$opt_c);
+#		$pte += editTilt($ens,$opt_t);
 	}
 	croak("$LADCP_file: no valid data\n") unless ($nvv > 0);
-	progress("\tcorrelation threshold (-c %d counts): %d velocites removed (%d%% of total)\n",$min_correlation,$cte,round(100*$cte/$nvv));
-#	progress("\tattitude threshold (-t %d deg): %d velocites removed (%d%% of total)\n",$max_tilt,$pte,round(100*$pte/$nvv));
+	progress("\tcorrelation threshold (-c %d counts): %d velocites removed (%d%% of total)\n",$opt_c,$cte,round(100*$cte/$nvv));
+#	progress("\tattitude threshold (-t %d deg): %d velocites removed (%d%% of total)\n",$opt_t,$pte,round(100*$pte/$nvv));
 }
 
 #-------------------------------------------------------------------
@@ -370,13 +438,15 @@
 if ($LADCP{BEAM_COORDINATES}) {
 	my($dummy);
 	progress("Calculating earth-coordinate velocities...\n");
-	progress("\tdiscarding velocities from beam $discard_velocities_from_beam\n")
-		if ($discard_velocities_from_beam);
+	progress("\tdiscarding velocities from beam $bad_beam\n")
+		if ($bad_beam);
 	$nvw = 0;
 	for ($ens=0; $ens<=$#{$LADCP{ENSEMBLE}}; $ens++) {
 		for (my($bin)=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
-			undef($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][$discard_velocities_from_beam-1])
-				if ($discard_velocities_from_beam);
+			if ($bad_beam) {
+				undef($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][$bad_beam-1]);
+				undef($LADCP{ENSEMBLE}[$ens]->{BT_VELOCITY}[$bin][$bad_beam-1]);
+			}
 			($LADCP{ENSEMBLE}[$ens]->{U}[$bin],
 			 $LADCP{ENSEMBLE}[$ens]->{V}[$bin],
 			 $LADCP{ENSEMBLE}[$ens]->{W}[$bin],
@@ -421,6 +491,8 @@
 			$LADCP{ENSEMBLE}[$ens]->{U_UNEDITED}[$bin] = $LADCP{ENSEMBLE}[$ens]->{U}[$bin];
 			$LADCP{ENSEMBLE}[$ens]->{V_UNEDITED}[$bin] = $LADCP{ENSEMBLE}[$ens]->{V}[$bin];
 			$LADCP{ENSEMBLE}[$ens]->{W_UNEDITED}[$bin] = $LADCP{ENSEMBLE}[$ens]->{W}[$bin];
+
+			$LADCP{ENSEMBLE}[$ens]->{W12}[$bin] = $LADCP{ENSEMBLE}[$ens]->{W34}[$bin] = $LADCP{ENSEMBLE}[$ens]->{W}[$bin];
 		}
 	}
 	progress("\t$nvw valid velocities in bins $LADCP_firstBin-$LADCP_lastBin\n");
@@ -439,12 +511,12 @@
 
 $evrm = $trrm = $worm = 0;
 for ($ens=0; $ens<=$#{$LADCP{ENSEMBLE}}; $ens++) {
-	$evrm += editErrVel($ens,$max_allowed_errvel);
+	$evrm += editErrVel($ens,$opt_e);
 	$worm += editWOutliers($ens,$per_ens_outliers_mad_limit);
 	$trrm += editTruncRange($ens,$truncate_farthest_valid_bins) if ($truncate_farthest_valid_bins > 0);
 }
-progress("\terror-velocity threshold (-e %.1f m/s): %d velocites removed (%d%% of total in bins $LADCP_firstBin-$LADCP_lastBin)\n",
-	$max_allowed_errvel,$evrm,round(100*$evrm/$nvw));
+progress("\terror-velocity threshold (-e %.2f m/s): %d velocites removed (%d%% of total in bins $LADCP_firstBin-$LADCP_lastBin)\n",
+	$opt_e,$evrm,round(100*$evrm/$nvw));
 progress("\tvertical-velocity outliers ($per_ens_outliers_mad_limit x mad): %d velocites removed (%d%% of total in bins $LADCP_firstBin-$LADCP_lastBin)\n",
 	$worm,round(100*$worm/$nvw));
 progress("\trange truncation (-z %d bins): %d velocites removed (%d%% of total in bins $LADCP_firstBin-$LADCP_lastBin)\n",
@@ -458,7 +530,7 @@
 progress("Calculating LADCP time-series...\n");
 
 ($firstGoodEns,$lastGoodEns,$LADCP_atbottom,$LADCP_w_gap_time) =
-	calcLADCPts(\%LADCP,$opt_s,$refLr_firstBin,$refLr_lastBin,$max_LADCP_reflr_vel_gap);
+	calcLADCPts(\%LADCP,$opt_s,$refLr_firstBin,$refLr_lastBin,$opt_g);
 croak("$LADCP_file: no good ensembles\n")
 	unless defined($firstGoodEns) && ($lastGoodEns-$firstGoodEns > 0);
 
@@ -520,11 +592,11 @@
 if (defined($first_bad_bin)) {
 	$fprm = $pte = 0;
 	for ($ens=0; $ens<=$#{$LADCP{ENSEMBLE}}; $ens++) {
-		$pte += editTilt($ens,$max_tilt);
+		$pte += editTilt($ens,$opt_t);
 		$fprm += editFarBins($ens,$first_bad_bin) if defined($first_bad_bin);
 	}
 	progress("\tattitude threshold (max_tilt = %d deg): %d velocites removed (%d%% of total)\n",
-		$max_tilt,$pte,round(100*$pte/$nvv));
+		$opt_t,$pte,round(100*$pte/$nvv));
 	progress("\tvelocities beyond bin $first_bad_bin (<%d%% valid values): %d velocites removed (%d%% of total in bins $LADCP_firstBin-$LADCP_lastBin)\n",
 		round(100*$per_bin_valid_frac_lim),$fprm,round(100*$fprm/$nvw));
 }
@@ -544,7 +616,7 @@
 
 $CTD_maxdepth = -1;
 
-do {
+do {																		# read data
 	croak("$0: cannot deal with non-numeric CTD elapsed time\n")
 		unless &antsNumbers($CTD_elapsed);
 	push(@{$CTD{ELAPSED}},$ants_[0][$CTD_elapsed]);
@@ -561,15 +633,22 @@
 $CTD{DT} = ($CTD{ELAPSED}[$#{$CTD{ELAPSED}}] - $CTD{ELAPSED}[0]) / $#{$CTD{ELAPSED}};
 progress("\t%d scans at %.1fHz\n",scalar(@{$CTD{DEPTH}}),1/$CTD{DT});
 
+$CTD{W_t}[0]  = $CTD{W_t} [@{$CTD{ELAPSED}}] = nan;							# calculate w-derivatives
+$CTD{W_tt}[0] = $CTD{W_tt}[@{$CTD{ELAPSED}}] = nan;
+for (my($s)=1; $s<@{$CTD{ELAPSED}}-1; $s++) {								# centered differences for both
+	$CTD{W_t} [$s] = ($CTD{W}[$s+1] - $CTD{W}[$s-1]) / (2*$CTD{DT});
+	$CTD{W_tt}[$s] = ($CTD{W}[$s+1] + $CTD{W}[$s-1] - 2*$CTD{W}[$s]) / $CTD{DT}**2;
+}
+
 croak("$0: CTD start depth must be numeric\n")
 	unless numberp($CTD{DEPTH}[0]);
-if (($CTD{DEPTH}[0] < -$CTD_neg_press_offset) && !defined($CTD_neg_press_offset)) {
-	$CTD_neg_press_offset = -1 * round($CTD{DEPTH}[0]);
+if (($CTD{DEPTH}[0] < -$opt_d) && !defined($opt_d)) {
+	$opt_d = -1 * round($CTD{DEPTH}[0]);
 }
-if ($CTD_neg_press_offset > 0) {
-	progress("\tadding $CTD_neg_press_offset dbar offset to pressure data\n");
-	for (my($i)=0; $i<@{$CTD{DEPTH}}; $i++) { $CTD{DEPTH}[$i] += $CTD_neg_press_offset; }
-	$CTD_maxdepth += $CTD_neg_press_offset;
+if ($opt_d > 0) {
+	progress("\tadding $opt_d dbar offset to pressure data\n");
+	for (my($i)=0; $i<@{$CTD{DEPTH}}; $i++) { $CTD{DEPTH}[$i] += $opt_d; }
+	$CTD_maxdepth += $opt_d;
 }
 
 progress("\tstart depth = %.1fm\n",$CTD{DEPTH}[0]);
@@ -593,9 +672,9 @@
 # Determine time lag
 #-------------------
 
-if (defined($first_guess_timelag)) {
+if (defined($opt_i)) {
 	progress("Setting initial time lag...\n");
-	$CTD{TIME_LAG} = $first_guess_timelag;
+	$CTD{TIME_LAG} = $opt_i;
 	progress("\t-i => elapsed(CTD) ~ elapsed(LADCP) + %.1fs\n",$CTD{TIME_LAG});
 } else {
 	progress("Guestimating time lag...\n");
@@ -618,28 +697,71 @@
 if ($opt_u) {
 	progress("\tskipping time lagging (-u)\n");
 } else {
-	$CTD{TIME_LAG} =														# stage 1: 1Hz; full cast
-		calc_lag($number_of_timelag_windows[0],$length_of_timelag_windows[0],int(1/$CTD{DT}+0.5),0);
+
+	#------------------------
+	# stage 1: 1Hz; full cast
+	#------------------------
+
+	$CTD{TIME_LAG} =														
+		calc_lag($number_of_timelag_windows[0],$length_of_timelag_windows[0],
+				 int(1/$CTD{DT}+0.5),$firstGoodEns,$lastGoodEns);
 	croak("$0: Cannot proceed without valid lag!\n") unless defined($CTD{TIME_LAG});
 	progress("\telapsed(CTD) ~ elapsed(LADCP) + %.2fs\n",$CTD{TIME_LAG});
-																			# stage 2: 24Hz; piece-wise
-	$CTD{TIME_LAG_DC} = calc_lag($number_of_timelag_windows[1],$length_of_timelag_windows[1],1,1);
-	progress("\tdowncast: elapsed(CTD) = elapsed(LADCP) + %.2fs\n",$CTD{TIME_LAG_DC})
-		if defined($CTD{TIME_LAG_DC});
-	$CTD{TIME_LAG_UC} = calc_lag($number_of_timelag_windows[1],$length_of_timelag_windows[1],1,-1);
-	progress("\tupcast  : elapsed(CTD) = elapsed(LADCP) + %.2fs\n",$CTD{TIME_LAG_UC})
-		if defined($CTD{TIME_LAG_UC});
+
+	#---------------------------------
+	# stage 2: piece-wise time lagging
+	#---------------------------------
+
+	my(@splits);
+	push(@splits,$firstGoodEns);
+	foreach my $s (split(/,/,$opt_p)) {
+		if ($s eq '+') {
+			push(@splits,$LADCP_atbottom);
+		} elsif (numberp($s)) {												# find ens for given LADCP elapsed time in min
+			my($ela) = $s*60;
+			my($ens) = $firstGoodEns + round($ela / $LADCP{MEAN_DT});		# first, guess
+			while ($LADCP{ENSEMBLE}[$ens]->{ELAPSED} > $ela) { $ens--; }	# then, correct
+			while ($LADCP{ENSEMBLE}[$ens]->{ELAPSED} < $ela) { $ens++; }
+			push(@splits,$ens);
+		} else {
+			warning(2,"ignoring non-numeric -p argument %s",$s);
+		}
+    }
+	push(@splits,$lastGoodEns);
 
-	croak("$0: Cannot proceed without either down- or upcast time-lag!\n")
-		unless defined($CTD{TIME_LAG_DC}) || defined($CTD{TIME_LAG_UC});
-	$CTD_time_lag_dc = $CTD{TIME_LAG_DC};									# if one lag is missing ...
-	$CTD_time_lag_uc = $CTD{TIME_LAG_UC};									# use other for entire ...
-	$CTD_time_lag_dc = $CTD_time_lag_uc unless defined($CTD_time_lag_dc);	# cast
-	$CTD_time_lag_uc = $CTD_time_lag_dc unless defined($CTD_time_lag_uc);
+	my($valid_lag);															# determine piece-wise lags
+	while (@splits > 1) {
+		push(@CTD_tl_fromEns,$splits[0]);
+		push(@CTD_tl_toEns,$splits[1]);
+		my($lag) = calc_lag($number_of_timelag_windows[1],$length_of_timelag_windows[1],
+							1,$splits[0],$splits[1]);
+		debugmsg("lag($splits[0],$splits[1]) = $lag\n");									
+		if (defined($lag)) {
+			progress("\tcast-piece: elapsed(CTD) = elapsed(LADCP) + %.2fs\n",$lag);
+			push(@CTD_time_lag,$lag);
+			$valid_lag = $#CTD_time_lag;
+		} else {
+			progress("\tcast-piece: time-lagging failed\n");
+			push(@CTD_time_lag,nan);
+		}
+		shift(@splits);
+	}
+			
+	croak("$0: Cannot proceed without at least one lag!\n")					# fill failed lag with surrounding data
+		unless defined($valid_lag);
+	while ($valid_lag < $#CTD_time_lag) {									# forward
+		$CTD_time_lag[$valid_lag+1] = $CTD_time_lag[$valid_lag];
+		$valid_lag++;
+	}
+	while ($valid_lag > 0) {												# backward
+		$CTD_time_lag[$valid_lag-1] = $CTD_time_lag[$valid_lag]
+			unless (numberp($CTD_time_lag[$valid_lag-1]));
+		$valid_lag--;
+	}
 }
 
-&antsAddParams('CTD_time_lag_dc',$CTD{TIME_LAG_DC},'CTD_time_lag_uc',$CTD{TIME_LAG_UC});
-undef($CTD{TIME_LAG}); 													# to avoid confusion
+&antsAddParams('CTD_time_lags',"@CTD_time_lag");
+undef($CTD{TIME_LAG}); 														# to avoid confusion, clear old 1Hz-based lag
 
 #------------------------------------------------
 # Merge CTD with LADCP data
@@ -648,60 +770,52 @@
 
 progress("Merging CTD with LADCP data...\n");
 
+my($cli) = 0;																	# current-lag index
+my($lag) = $CTD_time_lag[$cli];													# current lag
+
 for (my($skipped)=0,my($ens)=$firstGoodEns; $ens<=$lastGoodEns; $ens++) {
-	my($scan) = ($ens < $LADCP_atbottom) ?
-		int(($LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $CTD_time_lag_dc - $CTD{ELAPSED}[0]) / $CTD{DT} + 0.5) :
-		int(($LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $CTD_time_lag_uc - $CTD{ELAPSED}[0]) / $CTD{DT} + 0.5);
+
+	if ($ens > $CTD_tl_toEns[$cli]) {											# use correct lag piece
+		$cli++;
+		die("assertion failed!\n\ttest: \$cli(=$cli) <= \$#CTD_time_lag\n")
+			unless ($cli <= $#CTD_time_lag);
+		$lag = $CTD_time_lag[$cli];
+	}
+	
+	my($scan) = 
+		int(($LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $lag - $CTD{ELAPSED}[0]) / $CTD{DT} + 0.5);
 	if ($scan <= 0) {	# NB: must be <=, rather than <, or assertion below sometimes fails
 		$skipped++;
 		$firstGoodEns = $ens+1;
 		next;
 	}
 	if ($skipped > 0) {
-		$firstGoodEns++,$skipped++,next									# in gap
+		$firstGoodEns++,$skipped++,next											# in gap
 			unless defined($LADCP{ENSEMBLE}[$firstGoodEns]->{REFLR_W});
 		info("$skipped initial LADCP ensembles skipped because CTD data begin with LADCP in water\n");
 		$skipped = 0;
 	}
 	if ($scan > $#{$CTD{ELAPSED}}) {
-		while (!defined($LADCP{ENSEMBLE}[$ens-1]->{REFLR_W})) { $ens--; }	# in gap
+		while (!defined($LADCP{ENSEMBLE}[$ens-1]->{REFLR_W})) { $ens--; }		# in gap
 		info(sprintf("%d final LADCP ensembles skipped because CTD data end with LADCP in water\n",
 			$lastGoodEns-$ens+1));
 		$lastGoodEns = $ens-1;
 		last;
 	}
 
-	if ($ens < $LADCP_atbottom) {
-		die("assertion failed!\n" .
-			"\ttest: abs($LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $CTD_time_lag_dc - $CTD{ELAPSED}[$scan]) <= $CTD{DT}/2\n" .
-			"\tens = $ens, scan = $scan\n" .
-			sprintf("\tadjusted LADCP time = %f\n",$LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $CTD_time_lag_dc) .
-			sprintf("\tCTD($scan) time = %f\n",$CTD{ELAPSED}[$scan]) .
-			"=> Did you use SeaBird elapsed time? Don't!"
-	    ) unless (abs($LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $CTD_time_lag_dc - $CTD{ELAPSED}[$scan]) <= $CTD{DT}/2 + 1e-10);
-	} else {
-		die("assertion failed!\n" .
-			"\ttest: abs($LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $CTD_time_lag_uc - $CTD{ELAPSED}[$scan]) <= $CTD{DT}/2\n" .
-			"\tens = $ens, scan = $scan\n" .
-			sprintf("\tadjusted LADCP time = %f\n",$LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $CTD_time_lag_uc) .
-			sprintf("\tCTD($scan) time = %f\n",$CTD{ELAPSED}[$scan]) .
-			"=> Did you use SeaBird elapsed time? Don't!"
-	    ) unless (abs($LADCP{ENSEMBLE}[$ens]->{ELAPSED} + $CTD_time_lag_uc - $CTD{ELAPSED}[$scan]) <= $CTD{DT}/2 + 1e-10);
-	}
-
 	$LADCP{ENSEMBLE}[$ens]->{CTD_ELAPSED} = $CTD{ELAPSED}[$scan];		# elapsed field for output
 
 	if (defined($LADCP{ENSEMBLE}[$ens]->{REFLR_W})						# not a gap
 			&& numberp($CTD{DEPTH}[$scan])) {
 		$LADCP{ENSEMBLE}[$ens]->{REFLR_W_NOSSCORR} = $LADCP{ENSEMBLE}[$ens]->{REFLR_W};				
 	    $LADCP{ENSEMBLE}[$ens]->{REFLR_W} *= $CTD{SVEL}[$scan]/1500; 	# correct for sound-speed variations at source
-		croak(sprintf("\n$0: negative depth (%.1fm) in CTD file at elapsed(CTD) = %.1fs (use -a?)\n",
+		croak(sprintf("\n$0: negative depth (%.1fm) in CTD file at elapsed(CTD) = %.1fs (use -d?)\n",
 			$CTD{DEPTH}[$scan],$CTD{ELAPSED}[$scan]))
 				unless ($CTD{DEPTH}[$scan] >= 0);
 		$LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH} = $CTD{DEPTH}[$scan];
 		$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN} = $scan;
 		my($reflr_ocean_w) = $LADCP{ENSEMBLE}[$ens]->{REFLR_W} - $CTD{W}[$scan];
-		if (abs($reflr_ocean_w) <= $max_allowed_w) {
+		if (abs($reflr_ocean_w) <= $w_max_lim) {
 			$sumWsq += &SQR($reflr_ocean_w);
 			$nWsq++;
 			if ($LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH} > 100 &&
@@ -806,6 +920,30 @@
 	&{$post_merge_hook}($firstGoodEns,$lastGoodEns);
 }
 
+#----------------------------------------------------------------------
+# apply pressure-sensor acceleration correction (-a)
+#	- valid, but useless except for troubleshooting data sets (e.g. DIMES UK2)
+#	- useless, because ping-coherent error removal below does same job but better
+#	- it does not make sense to to use this with ping-coherent error removal enabled
+#----------------------------------------------------------------------
+
+if ($opt_a != 1) {
+	progress("Applying pressure-sensor acceleration correction...\n");
+	for ($ens=$firstGoodEns; $ens<=$lastGoodEns; $ens++) {
+		next unless numberp($CTD{W_tt}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}]);
+		my($acorr) = $opt_a * $CTD{W_tt}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}];
+		if (numberp($LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH})) {
+			for ($bin=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
+				next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
+				$LADCP{ENSEMBLE}[$ens]->{W}[$bin] -= $acorr;
+	        }
+	    }
+		if (numberp($LADCP{ENSEMBLE}[$ens]->{REFLR_W})) {
+			$LADCP{ENSEMBLE}[$ens]->{REFLR_W} -= $acorr;
+		}
+	}
+}
+
 #---------------------------------------------------------------------------
 # Depth-bin LADCP velocity data
 #
@@ -821,7 +959,7 @@
 #	   has only a minute effect
 #---------------------------------------------------------------------------
 
-progress("Binning velocities...\n");
+progress("Creating binned profiles at ${opt_o}m resolution...\n");
 
 my($min_depth) = 9e99;
 my($max_depth) = 0;
@@ -856,13 +994,16 @@
 				if numberp($LADCP{ENSEMBLE}[$ens]->{W34}[$bin]);
 		$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_W}[$bin] =
 			$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin] + $CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}];
-		my($bi) = $bindepth[$bin]/$output_bin_size;
+		my($bi) = $bindepth[$bin]/$opt_o;
 		push(@{$DNCAST{ENSEMBLE}[$bi]},$ens);
 		push(@{$DNCAST{ELAPSED}[$bi]},$CTD{ELAPSED}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}]);
 		push(@{$DNCAST{CTD_W}[$bi]},$CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}]);
+		push(@{$DNCAST{CTD_W_tt}[$bi]},$CTD{W_tt}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}]);
 		push(@{$DNCAST{BIN}[$bi]},$bin);
 		push(@{$DNCAST{DEPTH}[$bi]},$bindepth[$bin]);
 		push(@{$DNCAST{W}[$bi]},$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin]);
+		push(@{$DNCAST{W12}[$bi]},$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W12}[$bin]);
+		push(@{$DNCAST{W34}[$bi]},$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W34}[$bin]);
 	}
 }
 
@@ -870,6 +1011,8 @@
 	$DNCAST{MEAN_DEPTH}[$bi]  	= avg(@{$DNCAST{DEPTH}[$bi]});
 	$DNCAST{MEAN_ELAPSED}[$bi]	= avg(@{$DNCAST{ELAPSED}[$bi]});
 	$DNCAST{MEDIAN_W}[$bi] 	  	= median(@{$DNCAST{W}[$bi]});
+	$DNCAST{MEDIAN_W12}[$bi]  	= median(@{$DNCAST{W12}[$bi]});
+	$DNCAST{MEDIAN_W34}[$bi]  	= median(@{$DNCAST{W34}[$bi]});
 	$DNCAST{MAD_W}[$bi]		  	= mad2($DNCAST{MEDIAN_W}[$bi],@{$DNCAST{W}[$bi]});
 	$DNCAST{N_SAMP}[$bi]		= @{$DNCAST{W}[$bi]};
 }
@@ -904,13 +1047,16 @@
 				if numberp($LADCP{ENSEMBLE}[$ens]->{W34}[$bin]);
 		$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_W}[$bin] =
 			$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin] + $CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}];
-		my($bi) = $bindepth[$bin]/$output_bin_size;
+		my($bi) = $bindepth[$bin]/$opt_o;
 		push(@{$UPCAST{ENSEMBLE}[$bi]},$ens);
 		push(@{$UPCAST{ELAPSED}[$bi]},$CTD{ELAPSED}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}]);
 		push(@{$UPCAST{CTD_W}[$bi]},$CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}]);
+		push(@{$UPCAST{CTD_W_tt}[$bi]},$CTD{W_tt}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}]);
 		push(@{$UPCAST{BIN}[$bi]},$bin);
 		push(@{$UPCAST{DEPTH}[$bi]},$bindepth[$bin]);
 		push(@{$UPCAST{W}[$bi]},$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin]);
+		push(@{$UPCAST{W12}[$bi]},$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W12}[$bin]);
+		push(@{$UPCAST{W34}[$bi]},$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W34}[$bin]);
 	}
 }
 
@@ -918,64 +1064,92 @@
 	$UPCAST{MEAN_DEPTH}[$bi]  	= avg(@{$UPCAST{DEPTH}[$bi]});
 	$UPCAST{MEAN_ELAPSED}[$bi]	= avg(@{$UPCAST{ELAPSED}[$bi]});
 	$UPCAST{MEDIAN_W}[$bi] 	  	= median(@{$UPCAST{W}[$bi]});
+	$UPCAST{MEDIAN_W12}[$bi]  	= median(@{$UPCAST{W12}[$bi]});
+	$UPCAST{MEDIAN_W34}[$bi]  	= median(@{$UPCAST{W34}[$bi]});
 	$UPCAST{MAD_W}[$bi]		  	= mad2($UPCAST{MEDIAN_W}[$bi],@{$UPCAST{W}[$bi]});
 	$UPCAST{N_SAMP}[$bi]		= @{$UPCAST{W}[$bi]};
 }
 
-&antsAddParams('min_depth',$min_depth,'max_depth',$max_depth,					# plot area
+&antsAddParams('min_depth',$min_depth,'max_depth',$max_depth,					# plot range limits
 			   'min_ens',$LADCP{ENSEMBLE}[$firstGoodEns]->{NUMBER},
 			   'max_ens',$LADCP{ENSEMBLE}[$realLastGoodEns]->{NUMBER},
 			   'min_elapsed',$LADCP{ENSEMBLE}[$firstGoodEns]->{CTD_ELAPSED},
 			   'max_elapsed',$LADCP{ENSEMBLE}[$realLastGoodEns]->{CTD_ELAPSED});
 
 #------------------------------------------------------------------------------------------------------
-# remove single-ping noise
-#	- based on observation that without this step raw velocities tend to be strongly vertically striped
-#		=> residual CTD/LADCP mismatch errors & ADCP single-ping errors
-#	- remove ensemble-median residual from all vertical velocities; new residual calculated below
+# remove ping-coherent errors
+#	- error sources:
+#		1) acceleration-dependence of Paroscientific pressure measurements; O(10cm/s) [IWISE 28]
+#		2) residual CTD/LADCP mismatch errors; O(1cm/s) [Thurnherr, CWTMC 2011]
+#		3) ADCP short-term variability; O(1cm/s) for vertical?
+#	- two steps:
+#		- remove ensemble-median residual from all ocean vertical velocities
+#		- re-bin profiles
+#		- calculate new residuals
 #	- improves solution but can introduce errors in ensembles with strong outliers => median instead of
 #	  mean, and outlier filter above
 #------------------------------------------------------------------------------------------------------
 
 unless ($opt_q) {
-	progress("Removing single-ping residual noise...\n");
+	progress("Removing ping-coherent errors...\n");
 	
-	my($fe) = defined($CTD{TIME_LAG_DC}) ? $firstGoodEns    : $LADCP_atbottom;
-	my($le) = defined($CTD{TIME_LAG_UC}) ? $realLastGoodEns : $LADCP_atbottom;
+	for ($ens=$firstGoodEns; $ens<=$lastGoodEns; $ens++) {
+		next unless numberp($LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH});
 
-	for ($ens=$fe; $ens<=$le; $ens++) {
-		next unless numberp($LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH});
-		my(@residuals) = ();
+		my(@residuals) = ();												# calc median of residuals
 		my(@bindepth) = calc_binDepths($ens);
 		for ($bin=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
 			next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
-			my($bi) = $bindepth[$bin]/$output_bin_size;
+			my($bi) = $bindepth[$bin]/$opt_o;
 			push(@residuals,
 				$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin] -
 					(($ens < $LADCP_atbottom) ? $DNCAST{MEDIAN_W}[$bi]
 											  : $UPCAST{MEDIAN_W}[$bi]));
 		}
-		$LADCP{ENSEMBLE}[$ens]->{MEDIAN_RESIDUAL_W} = median(@residuals);
-		for ($bin=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
-			next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
+		$LADCP{ENSEMBLE}[$ens]->{MEDIAN_RESIDUAL_W} = median(@residuals);	# NB: can be nan!
+		
+		for ($bin=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {		# remove from ocean velocities
+			next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);			# also ensures that MEDIAN_RESIDUAL_W is not nan
 			$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin] -=
 				$LADCP{ENSEMBLE}[$ens]->{MEDIAN_RESIDUAL_W};
+			$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W12}[$bin] -=
+				$LADCP{ENSEMBLE}[$ens]->{MEDIAN_RESIDUAL_W}
+					if numberp($LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W12}[$bin]);
+			$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W34}[$bin] -=
+				$LADCP{ENSEMBLE}[$ens]->{MEDIAN_RESIDUAL_W}
+					if numberp($LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W34}[$bin]);
 		}
+		
+		$LADCP{ENSEMBLE}[$ens]->{REFLR_W} -=								# reflr_ocean_w is calculated below
+			$LADCP{ENSEMBLE}[$ens]->{MEDIAN_RESIDUAL_W}						# NB: this can be set to nan here
+				if numberp($LADCP{ENSEMBLE}[$ens]->{REFLR_W})
     }
 
-    progress("\tre-calculating profile mad...\n");
+	#------------------------------------------------------------
+
+    progress("\tre-binning profile data...\n");
     
-	for (my($bi)=0; $bi<=$#{$DNCAST{ENSEMBLE}}; $bi++) {						# bin data
+	for (my($bi)=0; $bi<=$#{$DNCAST{ENSEMBLE}}; $bi++) {					# bin data
 		for (my($i)=0; $i<@{$DNCAST{W}[$bi]}; $i++) {
-			$DNCAST{W}[$bi][$i] -= $LADCP{ENSEMBLE}[$DNCAST{ENSEMBLE}[$bi][$i]]->{MEDIAN_RESIDUAL_W};
+			$DNCAST{W}  [$bi][$i] -= $LADCP{ENSEMBLE}[$DNCAST{ENSEMBLE}[$bi][$i]]->{MEDIAN_RESIDUAL_W};
+			$DNCAST{W12}[$bi][$i] -= $LADCP{ENSEMBLE}[$DNCAST{ENSEMBLE}[$bi][$i]]->{MEDIAN_RESIDUAL_W};
+			$DNCAST{W34}[$bi][$i] -= $LADCP{ENSEMBLE}[$DNCAST{ENSEMBLE}[$bi][$i]]->{MEDIAN_RESIDUAL_W};
 		}
-		$DNCAST{MAD_W}[$bi] = mad2($DNCAST{MEDIAN_W}[$bi],@{$DNCAST{W}[$bi]});
+		$DNCAST{MEDIAN_W}  [$bi] = median(@{$DNCAST{W}[$bi]});
+		$DNCAST{MEDIAN_W12}[$bi] = median(@{$DNCAST{W12}[$bi]});
+		$DNCAST{MEDIAN_W34}[$bi] = median(@{$DNCAST{W34}[$bi]});
+		$DNCAST{MAD_W}	   [$bi] = mad2($DNCAST{MEDIAN_W}[$bi],@{$DNCAST{W}[$bi]});
 	}
 	for (my($bi)=0; $bi<=$#{$UPCAST{ENSEMBLE}}; $bi++) {
 		for (my($i)=0; $i<@{$UPCAST{W}[$bi]}; $i++) {
-			$UPCAST{W}[$bi][$i] -= $LADCP{ENSEMBLE}[$UPCAST{ENSEMBLE}[$bi][$i]]->{MEDIAN_RESIDUAL_W};
+			$UPCAST{W}  [$bi][$i] -= $LADCP{ENSEMBLE}[$UPCAST{ENSEMBLE}[$bi][$i]]->{MEDIAN_RESIDUAL_W};
+			$UPCAST{W12}[$bi][$i] -= $LADCP{ENSEMBLE}[$UPCAST{ENSEMBLE}[$bi][$i]]->{MEDIAN_RESIDUAL_W};
+			$UPCAST{W34}[$bi][$i] -= $LADCP{ENSEMBLE}[$UPCAST{ENSEMBLE}[$bi][$i]]->{MEDIAN_RESIDUAL_W};
 		}
-		$UPCAST{MAD_W}[$bi] = mad2($UPCAST{MEDIAN_W}[$bi],@{$UPCAST{W}[$bi]});
+		$UPCAST{MEDIAN_W}  [$bi] = median(@{$UPCAST{W}[$bi]});
+		$UPCAST{MEDIAN_W12}[$bi] = median(@{$UPCAST{W12}[$bi]});
+		$UPCAST{MEDIAN_W34}[$bi] = median(@{$UPCAST{W34}[$bi]});
+		$UPCAST{MAD_W}	   [$bi] = mad2($UPCAST{MEDIAN_W}[$bi],@{$UPCAST{W}[$bi]});
 	}
 
 } # unless ($opt_q);
@@ -996,7 +1170,7 @@
 			next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
 			push(@{$dc_bres[$bin]},
 					$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin]
-					- $DNCAST{MEDIAN_W}[$bindepth[$bin]/$output_bin_size]);
+					- $DNCAST{MEDIAN_W}[$bindepth[$bin]/$opt_o]);
 		}
 	}
 	for ($ens=$LADCP_atbottom; $ens<=$realLastGoodEns; $ens++) {					# upcast 
@@ -1006,7 +1180,7 @@
 			next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
 			push(@{$uc_bres[$bin]},
 					$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin]
-					- $UPCAST{MEDIAN_W}[$bindepth[$bin]/$output_bin_size]);
+					- $UPCAST{MEDIAN_W}[$bindepth[$bin]/$opt_o]);
 		}
 	}
 
@@ -1036,7 +1210,7 @@
 	my($sumSq) = my($n) = 0;
 	for (my($bi)=0; $bi<=$#{$BT{MEDIAN_W}}; $bi++) {
 		next unless defined($BT{MEDIAN_W}[$bi]);
-		next unless ($BT{N_SAMP}[$bi]>=$min_w_nsamp && $DNCAST{N_SAMP}[$bi]>=$min_w_nsamp && $UPCAST{N_SAMP}[$bi]>=$min_w_nsamp);
+		next unless ($BT{N_SAMP}[$bi]>=$opt_k && $DNCAST{N_SAMP}[$bi]>=$opt_k && $UPCAST{N_SAMP}[$bi]>=$opt_k);
 		$sumSq += ($BT{MEDIAN_W}[$bi] - $DNCAST{MEDIAN_W}[$bi]/2 - $UPCAST{MEDIAN_W}[$bi]/2)**2;
 		$n++;
 	}
@@ -1047,9 +1221,9 @@
 	}
 }
 
-#------------
-# full output
-#------------
+#------------------------
+# output all samples (-w)
+#------------------------
 
 # NB: residual field is calculated with respect to down-/upcast medians in -o-size bins
 
@@ -1057,118 +1231,116 @@
 	progress("Writing vertical-velocity data to $out_w...\n");
 
 	@antsNewLayout = ('ensemble','bin','elapsed','depth','CTD_depth','downcast',
-					  'w','w12','w34','residual','CTD_w','LADCP_w','errvel',
+					  'w','w12','w34','residual','CTD_w','CTD_w_tt','LADCP_w','errvel',
 					  'correlation','echo_amplitude','volume_scattering_coeff',
 					  'pitch','roll','tilt','heading','3_beam','svel');
 
 	open(STDOUT,"$out_w") || croak("$out_w: $!\n");
 
-	if (defined($CTD{TIME_LAG_DC})) {
-	  for ($ens=$firstGoodEns; $ens<$LADCP_atbottom; $ens++) {						# downcast
-		next unless numberp($LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH});
-		my(@bindepth) = calc_binDepths($ens);
-		for ($bin=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
-			next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
-			my($bi) = $bindepth[$bin]/$output_bin_size;
-			&antsOut(
-				$LADCP{ENSEMBLE}[$ens]->{NUMBER},$bin+1,
-				$CTD{ELAPSED}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
-				$bindepth[$bin],$LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH},1,
-				$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin],
-				$LADCP{BEAM_COORDINATES} ? $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W12}[$bin] : nan,
-				$LADCP{BEAM_COORDINATES} ? $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W34}[$bin] : nan,
-				$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin] - $DNCAST{MEDIAN_W}[$bi],
-				$CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
-				$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_W}[$bin],
-				$LADCP{ENSEMBLE}[$ens]->{ERRVEL}[$bin],
-				median(@{$LADCP{ENSEMBLE}[$ens]->{CORRELATION}[$bin]}),
-				median(@{$LADCP{ENSEMBLE}[$ens]->{ECHO_AMPLITUDE}[$bin]}),
-				$LADCP{ENSEMBLE}[$ens]->{SV}[$bin],
-				$LADCP{ENSEMBLE}[$ens]->{PITCH},
-				$LADCP{ENSEMBLE}[$ens]->{ROLL},
-				$LADCP{ENSEMBLE}[$ens]->{TILT},
-				$LADCP{ENSEMBLE}[$ens]->{HEADING},
-				(defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][0]) + 			# only works for beam coords
-				 defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][1]) +
-				 defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][2]) +
-				 defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][3])) < 4 ? 1 : 0,
-				$CTD{SVEL}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
-			);
-		} # for $bin
-	  } # for $ens
-	} # if defined dc time lag
-	
-	if (defined($CTD{TIME_LAG_UC})) {
-	  for ($ens=$LADCP_atbottom; $ens<=$realLastGoodEns; $ens++) {						# upcast 
-		next unless numberp($LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH});
-		my(@bindepth) = calc_binDepths($ens);
-		for ($bin=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
-			next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
-			my($bi) = $bindepth[$bin]/$output_bin_size;
-			&antsOut(
-				$LADCP{ENSEMBLE}[$ens]->{NUMBER},$bin+1,
-				$CTD{ELAPSED}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
-				$bindepth[$bin],$LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH},0,
-				$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin],
-				$LADCP{BEAM_COORDINATES} ? $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W12}[$bin] : nan,
-				$LADCP{BEAM_COORDINATES} ? $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W34}[$bin] : nan,
-				$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin] - $UPCAST{MEDIAN_W}[$bi],
-				$CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
-				$LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_W}[$bin],
-				$LADCP{ENSEMBLE}[$ens]->{ERRVEL}[$bin],
-				median(@{$LADCP{ENSEMBLE}[$ens]->{CORRELATION}[$bin]}),
-				median(@{$LADCP{ENSEMBLE}[$ens]->{ECHO_AMPLITUDE}[$bin]}),
-				$LADCP{ENSEMBLE}[$ens]->{SV}[$bin],
-				$LADCP{ENSEMBLE}[$ens]->{PITCH},
-				$LADCP{ENSEMBLE}[$ens]->{ROLL},
-				$LADCP{ENSEMBLE}[$ens]->{TILT},
-				$LADCP{ENSEMBLE}[$ens]->{HEADING},
-				(defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][0]) + 			# only works for beam coords
-				 defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][1]) +
-				 defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][2]) +
-				 defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][3])) < 4 ? 1 : 0,
-				$CTD{SVEL}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
-			);
-		} # for $bin
-	  } # for $ens
-	} # if defined uc time-lag
+	for ($ens=$firstGoodEns; $ens<$LADCP_atbottom; $ens++) {						# downcast
+	  next unless numberp($LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH});
+	  my(@bindepth) = calc_binDepths($ens);
+	  for ($bin=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
+		  next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
+		  my($bi) = $bindepth[$bin]/$opt_o;
+		  &antsOut(
+			  $LADCP{ENSEMBLE}[$ens]->{NUMBER},$bin+1,
+			  $CTD{ELAPSED}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+			  $bindepth[$bin],$LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH},1,
+			  $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin],
+			  $LADCP{BEAM_COORDINATES} ? $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W12}[$bin] : nan,
+			  $LADCP{BEAM_COORDINATES} ? $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W34}[$bin] : nan,
+			  $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin] - $DNCAST{MEDIAN_W}[$bi],
+			  $CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+			  $CTD{W_tt}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+			  $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_W}[$bin],
+			  $LADCP{ENSEMBLE}[$ens]->{ERRVEL}[$bin],
+			  median(@{$LADCP{ENSEMBLE}[$ens]->{CORRELATION}[$bin]}),
+			  median(@{$LADCP{ENSEMBLE}[$ens]->{ECHO_AMPLITUDE}[$bin]}),
+			  $LADCP{ENSEMBLE}[$ens]->{SV}[$bin],
+			  $LADCP{ENSEMBLE}[$ens]->{PITCH},
+			  $LADCP{ENSEMBLE}[$ens]->{ROLL},
+			  $LADCP{ENSEMBLE}[$ens]->{TILT},
+			  $LADCP{ENSEMBLE}[$ens]->{HEADING},
+			  (defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][0]) +			  # only works for beam coords
+			   defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][1]) +
+			   defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][2]) +
+			   defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][3])) < 4 ? 1 : 0,
+			  $CTD{SVEL}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+		  );
+	  } # for $bin
+	} # for $ens
+  
+	for ($ens=$LADCP_atbottom; $ens<=$realLastGoodEns; $ens++) {					  # upcast 
+	  next unless numberp($LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH});
+	  my(@bindepth) = calc_binDepths($ens);
+	  for ($bin=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
+		  next unless numberp($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
+		  my($bi) = $bindepth[$bin]/$opt_o;
+		  &antsOut(
+			  $LADCP{ENSEMBLE}[$ens]->{NUMBER},$bin+1,
+			  $CTD{ELAPSED}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+			  $bindepth[$bin],$LADCP{ENSEMBLE}[$ens]->{CTD_DEPTH},0,
+			  $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin],
+			  $LADCP{BEAM_COORDINATES} ? $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W12}[$bin] : nan,
+			  $LADCP{BEAM_COORDINATES} ? $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W34}[$bin] : nan,
+			  $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_OCEAN_W}[$bin] - $UPCAST{MEDIAN_W}[$bi],
+			  $CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+			  $CTD{W_tt}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+			  $LADCP{ENSEMBLE}[$ens]->{SSCORRECTED_W}[$bin],
+			  $LADCP{ENSEMBLE}[$ens]->{ERRVEL}[$bin],
+			  median(@{$LADCP{ENSEMBLE}[$ens]->{CORRELATION}[$bin]}),
+			  median(@{$LADCP{ENSEMBLE}[$ens]->{ECHO_AMPLITUDE}[$bin]}),
+			  $LADCP{ENSEMBLE}[$ens]->{SV}[$bin],
+			  $LADCP{ENSEMBLE}[$ens]->{PITCH},
+			  $LADCP{ENSEMBLE}[$ens]->{ROLL},
+			  $LADCP{ENSEMBLE}[$ens]->{TILT},
+			  $LADCP{ENSEMBLE}[$ens]->{HEADING},
+			  (defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][0]) +			  # only works for beam coords
+			   defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][1]) +
+			   defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][2]) +
+			   defined($LADCP{ENSEMBLE}[$ens]->{VELOCITY}[$bin][3])) < 4 ? 1 : 0,
+			  $CTD{SVEL}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+		  );
+	  } # for $bin
+	} # for $ens
 
 	&antsOut('EOF'); open(STDOUT,">&2");
 }
 	
-#---------------
-# Output profile
-#---------------
+#----------------------------
+# Output depth-binned profile
+#----------------------------
 
 if (defined($out_profile)) {
 	progress("Writing vertical-velocity profiles to <$out_profile>...\n");
 
-	@antsNewLayout = ('depth','dc_depth','dc_elapsed','dc_w','dc_w.mad','dc_w.nsamp',
-							  'uc_depth','uc_elapsed','uc_w','uc_w.mad','uc_w.nsamp',
+	@antsNewLayout = ('depth','dc_depth','dc_elapsed','dc_w','dc_w.mad','dc_w.nsamp','dc_w12','dc_w34',
+							  'uc_depth','uc_elapsed','uc_w','uc_w.mad','uc_w.nsamp','uc_w12','uc_w34',
 							  'elapsed','w','w.mad','w.nsamp',
 	                          'BT_w','BT_w.mad','BT_w.nsamp');
 
 	open(STDOUT,"$out_profile") || croak("$out_profile: $!\n");
 
-	undef(%DNCAST) unless defined($CTD{TIME_LAG_DC});
-	undef(%UPCAST) unless defined($CTD{TIME_LAG_UC});
 	for (my($bi)=0; $bi<=max($#{$DNCAST{ENSEMBLE}},$#{$UPCAST{ENSEMBLE}},$#{$BT{NSAMP}}); $bi++) {
-		&antsOut(($bi+0.5)*$output_bin_size,					# nominal depth
+		&antsOut(($bi+0.5)*$opt_o,					# nominal depth
 				 $DNCAST{MEAN_DEPTH}[$bi],$DNCAST{MEAN_ELAPSED}[$bi],
-				 $DNCAST{N_SAMP}[$bi]>=$min_w_nsamp?$DNCAST{MEDIAN_W}[$bi]:nan,
+				 $DNCAST{N_SAMP}[$bi]>=$opt_k?$DNCAST{MEDIAN_W}[$bi]:nan,
 				 $DNCAST{MAD_W}[$bi],$DNCAST{N_SAMP}[$bi],
+				 $DNCAST{MEDIAN_W12}[$bi],$DNCAST{MEDIAN_W34}[$bi],
 				 $UPCAST{MEAN_DEPTH}[$bi],$UPCAST{MEAN_ELAPSED}[$bi],
-				 $UPCAST{N_SAMP}[$bi]>=$min_w_nsamp?$UPCAST{MEDIAN_W}[$bi]:nan,
+				 $UPCAST{N_SAMP}[$bi]>=$opt_k?$UPCAST{MEDIAN_W}[$bi]:nan,
 				 $UPCAST{MAD_W}[$bi],$UPCAST{N_SAMP}[$bi],
+				 $UPCAST{MEDIAN_W12}[$bi],$UPCAST{MEDIAN_W34}[$bi],
 				 $DNCAST{MEAN_ELAPSED}[$bi]/2+$UPCAST{MEAN_ELAPSED}[$bi]/2,
-				 $DNCAST{N_SAMP}[$bi]+$UPCAST{N_SAMP}[$bi]>=$min_w_nsamp ?
+				 $DNCAST{N_SAMP}[$bi]+$UPCAST{N_SAMP}[$bi]>=$opt_k ?
 					($DNCAST{MEDIAN_W}[$bi]*$DNCAST{N_SAMP}[$bi]+$UPCAST{MEDIAN_W}[$bi]*$UPCAST{N_SAMP}[$bi]) / ($DNCAST{N_SAMP}[$bi]+$UPCAST{N_SAMP}[$bi]) :
 					nan,
-				 $DNCAST{N_SAMP}[$bi]+$UPCAST{N_SAMP}[$bi]>=$min_w_nsamp ?
+				 $DNCAST{N_SAMP}[$bi]+$UPCAST{N_SAMP}[$bi]>=$opt_k ?
 					 ($DNCAST{MAD_W}[$bi]*$DNCAST{N_SAMP}[$bi]+$UPCAST{MAD_W}[$bi]*$UPCAST{N_SAMP}[$bi]) / ($DNCAST{N_SAMP}[$bi]+$UPCAST{N_SAMP}[$bi]) :
 					 nan,
 				 $DNCAST{N_SAMP}[$bi]+$UPCAST{N_SAMP}[$bi],
-				 $BT{N_SAMP}[$bi]>=$min_w_nsamp?$BT{MEDIAN_W}[$bi]:nan,
+				 $BT{N_SAMP}[$bi]>=$opt_k?$BT{MEDIAN_W}[$bi]:nan,
 				 $BT{MAD_W}[$bi],$BT{N_SAMP}[$bi]
 		);
 	}
@@ -1184,7 +1356,7 @@
 
 	@antsNewLayout = ('ens','elapsed','downcast',
 					  'depth','xducer_sound_speed','pitch','gimbal_pitch','roll','tilt','heading',
-					  'CTD_w','LADCP_reflr_w','LADCP_reflr_w_err','LADCP_reflr_w_nosscorr',
+					  'CTD_w','CTD_w_tt','LADCP_reflr_w','LADCP_reflr_w.sig',
 					  'reflr_ocean_w');
 	open(STDOUT,"$out_timeseries") || croak("$out_timeseries: $!\n");
 	 
@@ -1204,10 +1376,10 @@
 				 $LADCP{ENSEMBLE}[$ens]->{TILT},
 				 $LADCP{ENSEMBLE}[$ens]->{HEADING},
 				 $CTD{W}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
+				 $CTD{W_tt}[$LADCP{ENSEMBLE}[$ens]->{CTD_SCAN}],
 				 $LADCP{ENSEMBLE}[$ens]->{REFLR_W},
-				 $LADCP{ENSEMBLE}[$ens]->{REFLR_W_ERR},
-				 $LADCP{ENSEMBLE}[$ens]->{REFLR_W_NOSSCORR},
-				 $reflr_w);
+				 $LADCP{ENSEMBLE}[$ens]->{REFLR_W_STDDEV},
+				 $reflr_oc_w);
 	}
 
 	&antsOut('EOF'); open(STDOUT,">&2");
--- a/LWplot_BR	Sat Mar 23 13:45:31 2013 +0000
+++ b/LWplot_BR	Thu Nov 21 09:07:17 2013 -0500
@@ -2,9 +2,9 @@
 #======================================================================
 #					 L W P L O T _ B R 
 #                    doc: Mon Oct 17 10:57:12 2011
-#                    dlm: Wed Apr 18 10:32:12 2012
+#                    dlm: Wed Oct 30 00:37:51 2013
 #                    (c) 2011 A.M. Thurnherr
-#                    uE-Info: 15 0 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 16 0 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -12,6 +12,7 @@
 #	Nov 14, 2011: - added file layout check
 #	Mar 12, 2012: - sh -> ksh as this does not work with /bin/sh on MacOSX 10.6.4
 #	Apr 12, 2012: - made re-entrant
+#   Oct 30, 2103: - got rid of non-portable echo -e
 
 #--------------------------------------------------
 # Usage
@@ -70,7 +71,7 @@
 U=-R0/1/0/1
 X=-JX10/-10
 
-echo -e "0 0.5\n0 `echo $max_bin+0.5|bc`" | psxy -P -K $R $X > "$eps_file"
+{ echo 0 0.5; echo 0 `echo $max_bin+0.5|bc`; } | psxy -P -K $R $X > "$eps_file"
 
 awk '{print $2, $1}' $TMPFILE | psxy -O -K -Mn $R $X -W4/coral >> "$eps_file"
 awk '{print $5, $1}' $TMPFILE | psxy -O -K -Mn $R $X -W4/SeaGreen >> "$eps_file"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LWplot_CAE	Thu Nov 21 09:07:17 2013 -0500
@@ -0,0 +1,104 @@
+#!/bin/ksh
+#======================================================================
+#                    L W P L O T _ C A E 
+#                    doc: Wed May 15 19:35:58 2013
+#                    dlm: Wed Oct 30 00:47:39 2013
+#                    (c) 2013 A.M. Thurnherr
+#                    uE-Info: 80 28 NIL 0 0 72 2 2 4 NIL ofnI
+#======================================================================
+
+# HISTORY:
+#	May 15, 2013: - created from [LWplot_BR]
+#	May 16, 2013: - fiddled
+#	Oct 30, 2013: - BUG: debug statement had been left in code
+#   Oct 30, 2103: - got rid of non-portable echo -e
+
+#--------------------------------------------------
+# Usage
+#--------------------------------------------------
+
+USAGE="Usage: $0 <eps-file> [in-file]"
+	[ $# -eq 2 ] && exec <"$2" "$0" "$1"
+	[ $# -ne 1 ] && { echo $USAGE >&2; exit 1; }
+eps_file="$1"
+
+#--------------------------------------------------
+# Read Header Data
+#--------------------------------------------------
+
+while [ -z "$fields" ]
+do
+	read line
+    [ ! -t 1 ] && echo "$line"
+	[ -z "$out_basename" ] && out_basename=`expr -- "$line" : '#ANTS#PARAMS#.*out_basename{\([^}]*\)}`
+	[ -z "$run_label" ] && run_label=`expr -- "$line" : '#ANTS#PARAMS#.*run_label{\([^}]*\)}`
+	[ -z "$fields" ] && fields=`expr -- "$line" : '#ANTS#FIELDS# \(.*\)' | sed -e s/{//g -e s/}//g`
+done
+
+set -- $fields
+[ "$3" = downcast -a "${12}" = CTD_w_tt -a "${15}" = reflr_ocean_w ] || {
+		echo "$0: file layout error" >&2
+		exit 1
+}
+
+#--------------------------------------------------
+# Plot Data
+#--------------------------------------------------
+
+eps_file="$PWD/$eps_file"	# make outfile name absolute (hopefully, it is not already...)
+mkdir /tmp/$$				# GMT makes tmpfiles and is not reentrant
+cd /tmp/$$
+
+TMPFILE=/tmp/$$.LWplot_BR
+if [ ! -t 1 ]
+then
+	tee $TMPFILE
+else
+	cat > $TMPFILE
+fi
+
+[ -f .gmtdefaults4 ] ||
+	gmtset	PAPER_MEDIA letter+ \
+			LABEL_FONT_SIZE 14 ANNOT_FONT_SIZE_PRIMARY 14 \
+			WANT_EURO_FONT true \
+	        PLOT_DEGREE_FORMAT ddd:mm:ssF
+
+#R=-R-0.8/0.8/-0.3/0.3
+R=-R-2.0/2.0/-0.3/0.3
+U=-R0/1/0/1
+X=-JX10/10
+
+awk '{print $3, $12, $15}' $TMPFILE |
+	Cat -QS1:1 -F'$2,$3' |
+	psxy -P -K -Mn $R $X -Sc0.1 -Gcoral > "$eps_file"
+	
+awk '{print $3, $12, $15}' $TMPFILE |
+	Cat -QS1:0 -F'$2,$3' |
+	psxy -O -K -Mn $R $X -Sc0.1 -GSeaGreen >> "$eps_file"
+	
+{ echo -2.0 0; echo 2.0 0; } | psxy -O -K $R $X -W2/gray30 >> "$eps_file"
+{ echo 0 -0.3; echo 0 0.3; } | psxy -O -K $R $X -W2/gray30 >> "$eps_file"
+
+{ echo -2.0 -0.2; echo 2.0 -0.2; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+{ echo -2.0 -0.1; echo 2.0 -0.1; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+{ echo -2.0  0.1; echo 2.0  0.1; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+{ echo -2.0  0.2; echo 2.0  0.2; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+
+{ echo -1.5 -0.3; echo -1.5 0.3; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+{ echo -1.0 -0.3; echo -1.0 0.3; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+{ echo -0.5 -0.3; echo -0.5 0.3; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+{ echo  0.5 -0.3; echo  0.5 0.3; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+{ echo  1.0 -0.3; echo  1.0 0.3; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+{ echo  1.5 -0.3; echo  1.5 0.3; } | psxy -O -K $R $X -W1/gray70 >> "$eps_file"
+
+echo 0.047 0.965 12 0 0 TL $out_basename $run_label| pstext -O -K $U $X >> "$eps_file"
+
+psbasemap -O -K $R $X -Bf0.1a1:"CTD d@+2@+z/dt@+2@+ [ms@+-3@+]":/f0.01a0.1:"reference-layer ocean w [ms@+-1@+]":WeSn >> "$eps_file"
+psbasemap -O $R $X -B/a100-99W >> "$eps_file"
+
+rm $TMPFILE
+fixbb "$eps_file"
+
+cd "$PWD"
+rm -rf /tmp/$$
+
--- a/LWplot_Sv	Sat Mar 23 13:45:31 2013 +0000
+++ b/LWplot_Sv	Thu Nov 21 09:07:17 2013 -0500
@@ -2,9 +2,9 @@
 #======================================================================
 #					 L W P L O T _ S V 
 #                    doc: Sat Oct 15 13:42:50 2011
-#                    dlm: Wed Apr 18 10:32:58 2012
+#                    dlm: Thu May 16 15:22:39 2013
 #                    (c) 2011 A.M. Thurnherr
-#                    uE-Info: 16 0 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 83 26 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -13,6 +13,7 @@
 #	Nov 14, 2011: - added file layout check
 #	Mar 12, 2012: - sh -> ksh as this does not work with /bin/sh on MacOSX 10.6.4
 #   Apr 12, 2012: - made re-entrant
+#	May 16, 2013: - adapted to file-layout changes
 
 #--------------------------------------------------
 # Usage
@@ -43,7 +44,7 @@
 done
 
 set -- $fields
-[ "$1" = ensemble -a "$4" = depth -a "${16}" = volume_scattering_coeff ] || {
+[ "$1" = ensemble -a "$4" = depth -a "${17}" = volume_scattering_coeff ] || {
 	echo "$0: file layout error" >&2
 	exit 1
 }
@@ -79,7 +80,7 @@
 ens_width=`echo "scale=5;10/($max_ens-$min_ens+1)"|bc`
 bin_length=`echo "scale=5;10*$ADCP_bin_length/($max_depth-$min_depth+$ADCP_bin_length)"|bc`
 
-awk "{print \$1, \$4, \$16, $ens_width, $bin_length}" $TMPFILE \
+awk "{print \$1, \$4, \$17, $ens_width, $bin_length}" $TMPFILE \
 	| psxy -P -K $R $X $C -Sr > "$eps_file"
 	
 echo 0.02 0.02 12 0 0 TL $out_basename $run_label | pstext -O -K $U $X >> "$eps_file"
--- a/LWplot_TL	Sat Mar 23 13:45:31 2013 +0000
+++ b/LWplot_TL	Thu Nov 21 09:07:17 2013 -0500
@@ -2,9 +2,9 @@
 #======================================================================
 #                    L W P L O T _ T L 
 #                    doc: Thu Oct 13 10:51:49 2011
-#                    dlm: Tue Oct 16 13:02:45 2012
+#                    dlm: Wed Oct 30 00:38:34 2013
 #                    (c) 2011 A.M. Thurnherr
-#                    uE-Info: 20 52 NIL 0 0 72 0 2 4 NIL ofnI
+#                    uE-Info: 23 0 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -18,6 +18,8 @@
 #	Oct 12, 2012: - split dc/uc time lagging
 #				  - reduced number of xtic labels 
 #	Oct 16, 2012: - renamed elapsed to elapsed.LADCP
+#	Mar 23, 2013: - adapted to piece-wice time lagging
+#   Oct 30, 2103: - got rid of non-portable echo -e
 
 USAGE="Usage: $0 <eps-file> [in-file]"
 	[ $# -eq 2 ] && exec <"$2" "$0" "$1"
@@ -33,8 +35,8 @@
 	[ -z "$min_elapsed" ] && min_elapsed=`expr -- "$line" : '#ANTS#PARAMS#.*elapsed.min{\([^}]*\)}`
 	[ -z "$max_elapsed" ] && max_elapsed=`expr -- "$line" : '#ANTS#PARAMS#.*elapsed.max{\([^}]*\)}`
 	[ -z "$bot_elapsed" ] && bot_elapsed=`expr -- "$line" : '#ANTS#PARAMS#.*elapsed.bot{\([^}]*\)}`
-	[ -z "$best_scan_offset_dc" ] && best_scan_offset_dc=`expr -- "$line" : '#ANTS#PARAMS#.*best_scan_offset\.dc{\([^}]*\)}`
-	[ -z "$best_scan_offset_uc" ] && best_scan_offset_uc=`expr -- "$line" : '#ANTS#PARAMS#.*best_scan_offset\.uc{\([^}]*\)}`
+	[ -z "$best_scan_offsets" ] && best_scan_offsets=`expr -- "$line" : '#ANTS#PARAMS#.*best_scan_offsets{\([^}]*\)}`
+	[ -z "$to_elapsed_limits" ] && to_elapsed_limits=`expr -- "$line" : '#ANTS#PARAMS#.*to_elapsed_limits{\([^}]*\)}`
 	[ -z "$fields" ] && fields=`expr -- "$line" : '#ANTS#FIELDS# \(.*\)' | sed -e s/{//g -e s/}//g`
 done
 
@@ -78,11 +80,26 @@
 	
 echo 0.02 0.98 12 0 0 TL $out_basename $run_label | pstext -O -K $U $J >> "$eps_file"
 
-echo -e "`echo $min_elapsed/60|bc` $best_scan_offset_dc\n`echo $bot_elapsed/60+1|bc` $best_scan_offset_dc" \
-	| psxy -O -K $R $J -W4/coral >> "$eps_file"
-echo -e "`echo $bot_elapsed/60|bc` $best_scan_offset_uc\n`echo $max_elapsed/60+1|bc` $best_scan_offset_uc" \
-	| psxy -O $R $J -W4/SeaGreen >> "$eps_file"
+fel=$min_elapsed			# from-elapsed limit
+set -- $best_scan_offsets
+while [ -n "$1" ]
+do
+	bso=$1
+	shift
+	best_scan_offsets=$@
+	
+	set -- $to_elapsed_limits
+	tel=$1
+	shift
+	to_elapsed_limits=$@
 
+	{ echo `echo $fel/60|bc` $bso; echo `echo $tel/60+1|bc` $bso; } \
+		| psxy -O -K $R $J -W4/grey20 >> "$eps_file"
+
+	fel=$tel
+	set -- $best_scan_offsets
+done
+	
 rm $TMPFILE
 fixbb "$eps_file"
 
--- a/LWplot_corr	Sat Mar 23 13:45:31 2013 +0000
+++ b/LWplot_corr	Thu Nov 21 09:07:17 2013 -0500
@@ -2,9 +2,9 @@
 #======================================================================
 #					 L W P L O T _ C O R R 
 #                    doc: Sat Oct 15 13:42:50 2011
-#                    dlm: Wed Apr 18 10:34:44 2012
+#                    dlm: Thu May 16 15:23:26 2013
 #                    (c) 2011 A.M. Thurnherr
-#                    uE-Info: 16 0 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 82 26 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -13,6 +13,7 @@
 #	Nov 14, 2011: - added file layout check
 #	Mar 12, 2012: - sh -> ksh as this does not work with /bin/sh on MacOSX 10.6.4
 #   Apr 12, 2012: - made re-entrant
+#	May 16, 2013: - adapted to file layout change
 
 #--------------------------------------------------
 # Usage
@@ -42,7 +43,7 @@
 done
 
 set -- $fields
-[ "$1" = ensemble -a "$4" = depth -a "${14}" = correlation ] || {
+[ "$1" = ensemble -a "$4" = depth -a "${15}" = correlation ] || {
 	echo "$0: file layout error" >&2
 	exit 1
 }
@@ -78,7 +79,7 @@
 ens_width=`echo "scale=5;10/($max_ens-$min_ens+1)"|bc`
 bin_length=`echo "scale=5;10*$ADCP_bin_length/($max_depth-$min_depth+$ADCP_bin_length)"|bc`
 
-awk "{print \$1, \$4, \$14, $ens_width, $bin_length}" $TMPFILE \
+awk "{print \$1, \$4, \$15, $ens_width, $bin_length}" $TMPFILE \
 	| psxy -P -K $R $X $C -Sr > "$eps_file"
 	
 echo 0.02 0.02 12 0 0 TL $out_basename $run_label | pstext -O -K $U $X >> "$eps_file"
--- a/LWplot_prof	Sat Mar 23 13:45:31 2013 +0000
+++ b/LWplot_prof	Thu Nov 21 09:07:17 2013 -0500
@@ -2,9 +2,9 @@
 #======================================================================
 #					 L W P L O T _ P R O F 
 #                    doc: Fri Oct 14 09:42:36 2011
-#                    dlm: Wed Apr 18 10:35:19 2012
+#                    dlm: Wed Oct 30 00:39:48 2013
 #                    (c) 2011 A.M. Thurnherr
-#                    uE-Info: 107 0 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 89 0 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -16,6 +16,8 @@
 #	Nov 14, 2011: - added file layout check
 #	Mar 12, 2012: - sh -> ksh as this does not work with /bin/sh on MacOSX 10.6.4
 #   Apr 12, 2012: - made re-entrant
+#	May 15, 2013: - BUG: plot separation lines/shading did not work any more
+#   Oct 30, 2103: - got rid of non-portable echo -e
 
 #--------------------------------------------------
 # Usage
@@ -43,8 +45,8 @@
 
 set -- $fields
 [ "$1" = depth -a "$4" = dc_w -a "$5" = dc_w.mad -a "$6" = dc_w.nsamp -a \
-  "$9" = uc_w  -a "${10}" = uc_w.mad -a "${11}" = uc_w.nsamp -a \
-  "${16}" = BT_w  -a "${17}" = BT_w.mad -a "${18}" = BT_w.nsamp ] || {
+  "${11}" = uc_w  -a "${12}" = uc_w.mad -a "${13}" = uc_w.nsamp -a \
+  "${20}" = BT_w  -a "${21}" = BT_w.mad -a "${22}" = BT_w.nsamp ] || {
 		echo "$0: file layout error" >&2
 		exit 1
 }
@@ -76,24 +78,29 @@
 U=-R0/1/0/1
 X=-JX10/-10
 
-echo "0 $min_depth\n0 $max_depth" | psxy -P -K $R $X > "$eps_file"
-echo "0.07 $min_depth\n0.07 $max_depth\n0.18 $max_depth\n0.18 $min_depth" | psxy -O -K $R $X -L -G200 >> "$eps_file"
-echo "50 $min_depth\n50 $max_depth" | psxy -O -K $R2 $X >> "$eps_file"
-echo "100 $min_depth\n100 $max_depth" | psxy -O -K $R2 $X >> "$eps_file"
-echo "150 $min_depth\n150 $max_depth" | psxy -O -K $R2 $X >> "$eps_file"
+# FRAME
+{ echo 0 $min_depth; echo 0 $max_depth; } | psxy -P -K $R $X > "$eps_file"
+{ echo 0.07 $min_depth; echo 0.07 $max_depth; echo 0.18 $max_depth; echo 0.18 $min_depth; } | psxy -O -K $R $X -L -G200 >> "$eps_file"
+{ echo 50 $min_depth; echo 50 $max_depth; } | psxy -O -K $R2 $X >> "$eps_file"
+{ echo 100 $min_depth; echo 100 $max_depth; } | psxy -O -K $R2 $X >> "$eps_file"
+{ echo 150 $min_depth; echo 150 $max_depth; } | psxy -O -K $R2 $X >> "$eps_file"
 
+# VERTICAL VELOCITIES
 awk '{print $4, $1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4/coral >> "$eps_file"
-awk '{print $9, $1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4/SeaGreen >> "$eps_file"
-awk '{print $16,$1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4/black >> "$eps_file"
+awk '{print $11,$1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4/SeaGreen >> "$eps_file"
+awk '{print $20,$1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4/black >> "$eps_file"
 	
+# MEAN ABSOLUTE DEVIATIONS (COMBINED SOLUTION)
 awk '{print  $5,$1, $4}' $TMPFILE | grep -vi nan | psxy -O -K -N  $R $X -Sc0.1c -Gcoral >> "$eps_file"
-awk '{print $10,$1, $9}' $TMPFILE | grep -vi nan | psxy -O -K -N  $R $X -Sc0.1c -GSeaGreen >> "$eps_file"
-awk '{print $17,$1,$16}' $TMPFILE | grep -vi nan | psxy -O -K -N  $R $X -Sc0.1c -Gblack >> "$eps_file"
+awk '{print $12,$1,$11}' $TMPFILE | grep -vi nan | psxy -O -K -N  $R $X -Sc0.1c -GSeaGreen >> "$eps_file"
+awk '{print $21,$1,$20}' $TMPFILE | grep -vi nan | psxy -O -K -N  $R $X -Sc0.1c -Gblack >> "$eps_file"
 
-awk '{print  $6,$1,$4}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/coral >> "$eps_file"
-awk '{print $11,$1,$9}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/SeaGreen >> "$eps_file"
-awk '{print $18,$1,$16}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/black >> "$eps_file"
+# NUMBER OF SAMPLES (COMBINED SOLUTION)
+awk '{print  $6,$1, $4}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/coral >> "$eps_file"
+awk '{print $13,$1,$11}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/SeaGreen >> "$eps_file"
+awk '{print $22,$1,$20}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/black >> "$eps_file"
 
+# LABELS
 echo 0.02 0.02 12 0 0 TL $out_basename $run_label | pstext -O -K $U $X >> "$eps_file"
 echo 0.6 0.98 12 0 0 BR m.a.d. | pstext -O -K $U $X >> "$eps_file"
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LWplot_prof_2beam	Thu Nov 21 09:07:17 2013 -0500
@@ -0,0 +1,125 @@
+#!/bin/ksh
+#======================================================================
+#					 L W P L O T _ P R O F _ 2 B E A M 
+#                    doc: Fri Oct 14 09:42:36 2011
+#                    dlm: Wed Oct 30 00:36:31 2013
+#                    (c) 2011 A.M. Thurnherr
+#                    uE-Info: 12 51 NIL 0 0 72 2 2 4 NIL ofnI
+#======================================================================
+
+# HISTORY:
+#	May 15, 2013: - created from [LWplot_prof]
+#	Oct 30, 2103: - got rid of non-portable echo -e
+
+# NOTES:
+#	- this version plots 2-beam solutions instead of final w
+
+#--------------------------------------------------
+# Usage
+#--------------------------------------------------
+
+USAGE="Usage: $0 <eps-file> [in-file]"
+	[ $# -eq 2 ] && exec <"$2" "$0" "$1"
+	[ $# -ne 1 ] && { echo $USAGE >&2; exit 1; }
+eps_file="$1"
+
+#--------------------------------------------------
+# Read Header Data
+#--------------------------------------------------
+
+while [ -z "$fields" ]
+do
+	read line
+    [ ! -t 1 ] && echo "$line"
+	[ -z "$out_basename" ] && out_basename=`expr -- "$line" : '#ANTS#PARAMS#.*out_basename{\([^}]*\)}`
+	[ -z "$run_label" ] && run_label=`expr -- "$line" : '#ANTS#PARAMS#.*run_label{\([^}]*\)}`
+	[ -z "$min_depth" ] && min_depth=`expr -- "$line" : '#ANTS#PARAMS#.*min_depth{\([^}]*\)}`
+	[ -z "$max_depth" ] && max_depth=`expr -- "$line" : '#ANTS#PARAMS#.*max_depth{\([^}]*\)}`
+	[ -z "$fields" ] && fields=`expr -- "$line" : '#ANTS#FIELDS# \(.*\)' | sed -e s/{//g -e s/}//g`
+done
+
+set -- $fields
+[ "$1" = depth -a "$7" = dc_w12 -a "$8" = dc_w34 -a "$5" = dc_w.mad -a "$6" = dc_w.nsamp -a \
+  "${14}" = uc_w12 -a "${15}" = uc_w34 -a "${12}" = uc_w.mad -a "${13}" = uc_w.nsamp -a \
+  "${20}" = BT_w  -a "${21}" = BT_w.mad -a "${22}" = BT_w.nsamp ] || {
+		echo "$0: file layout error" >&2
+		exit 1
+}
+
+#--------------------------------------------------
+# Plot Data
+#--------------------------------------------------
+
+eps_file="$PWD/$eps_file"	# make outfile name absolute (hopefully, it is not already...)
+mkdir /tmp/$$				# GMT makes tmpfiles and is not reentrant
+cd /tmp/$$
+
+TMPFILE=/tmp/$$.LWplot_prof
+if [ ! -t 1 ]
+then
+	tee $TMPFILE
+else
+	cat > $TMPFILE
+fi
+
+[ -f .gmtdefaults4 ] ||
+	gmtset	PAPER_MEDIA letter+ \
+			LABEL_FONT_SIZE 14 ANNOT_FONT_SIZE_PRIMARY 14 \
+			WANT_EURO_FONT true \
+	        PLOT_DEGREE_FORMAT ddd:mm:ssF
+
+R=-R-0.07/0.35/$min_depth/$max_depth
+R2=-R-200/200/$min_depth/$max_depth
+U=-R0/1/0/1
+X=-JX10/-10
+
+# FRAME
+{ echo 0 $min_depth; echo 0 $max_depth; } | psxy -P -K $R $X > "$eps_file"
+{ echo 0.07 $min_depth; echo 0.07 $max_depth; echo 0.18 $max_depth; echo 0.18 $min_depth; } | psxy -O -K $R $X -L -G200 >> "$eps_file"
+{ echo 50 $min_depth; echo 50 $max_depth; } | psxy -O -K $R2 $X >> "$eps_file"
+{ echo 100 $min_depth; echo 100 $max_depth; } | psxy -O -K $R2 $X >> "$eps_file"
+{ echo 150 $min_depth; echo 150 $max_depth; } | psxy -O -K $R2 $X >> "$eps_file"
+
+# VERTICAL VELOCITIES (2-BEAM SOLUTIONS)
+awk '{print $7, $1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4,coral,6_2:0 >> "$eps_file"
+awk '{print $8, $1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4,coral,4_6:0 >> "$eps_file"
+awk '{print $14,$1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4,SeaGreen,6_2:0 >> "$eps_file"
+awk '{print $15,$1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4,SeaGreen,4_6:0 >> "$eps_file"
+awk '{print $20,$1}' $TMPFILE | psxy -O -K -N -Mn $R $X -W4,black >> "$eps_file"
+	
+# MEAN ABSOLUTE DEVIATIONS (COMBINED SOLUTION)
+awk '{print  $5,$1, $4}' $TMPFILE | grep -vi nan | psxy -O -K -N  $R $X -Sc0.1c -Gcoral >> "$eps_file"
+awk '{print $12,$1,$11}' $TMPFILE | grep -vi nan | psxy -O -K -N  $R $X -Sc0.1c -GSeaGreen >> "$eps_file"
+awk '{print $21,$1,$20}' $TMPFILE | grep -vi nan | psxy -O -K -N  $R $X -Sc0.1c -Gblack >> "$eps_file"
+
+# NUMBER OF SAMPLES (COMBINED SOLUTION)
+awk '{print  $6,$1, $4}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/coral >> "$eps_file"
+awk '{print $13,$1,$11}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/SeaGreen >> "$eps_file"
+awk '{print $22,$1,$20}' $TMPFILE | sed '/nan/s/.*/nan/' | psxy -O -K -N -Mn $R2 $X -W1/black >> "$eps_file"
+
+# LABELS
+echo 0.02 0.02 12 0 0 TL $out_basename $run_label | pstext -O -K $U $X >> "$eps_file"
+echo 0.6 0.98 12 0 0 BR m.a.d. | pstext -O -K $U $X >> "$eps_file"
+
+# AXES
+if [ 0 -eq `echo "($max_depth-$min_depth)>1000"|bc` ]
+then
+	depth_tics=f10a100
+else
+	depth_tics=f100a500
+fi
+
+psbasemap -O -K $R $X -Bf0.01a10-10.05:"Vertical Velocity [m/s]                               ":/$depth_tics:"Depth [m]":WeS >> "$eps_file"
+psbasemap -O -K $R $X -Ba10-9.95S >> "$eps_file"
+psbasemap -O -K $R $X -Ba10-9.85S >> "$eps_file"
+
+psbasemap -O -K $R2 $X -Bf10a1000-950:"                                     # of Samples":N >> "$eps_file"
+psbasemap -O -K $R2 $X -Ba1000-900N >> "$eps_file"
+psbasemap -O $R2 $X -Ba1000-850N >> "$eps_file"
+		 
+rm $TMPFILE
+fixbb "$eps_file"
+
+cd "$PWD"
+rm -rf /tmp/$$
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LWplot_spec	Thu Nov 21 09:07:17 2013 -0500
@@ -0,0 +1,133 @@
+#!/bin/ksh
+#======================================================================
+#					 L W P L O T _ S P E C 
+#                    doc: Thu Sep  5 18:23:41 2013
+#                    dlm: Wed Nov  6 23:33:40 2013
+#                    (c) 2013 A.M. Thurnherr
+#                    uE-Info: 120 10 NIL 0 0 72 2 2 4 NIL ofnI
+#======================================================================
+
+# HISTORY:
+#	Sep  5, 2013: - created from LWplot_prof
+#   Oct 30, 2103: - got rid of non-portable echo -e
+#	Nov  6, 2013: - add interpolation of missing values
+
+#--------------------------------------------------
+# Usage
+#--------------------------------------------------
+
+USAGE="Usage: $0 <eps-file> [in-file]"
+	[ $# -eq 2 ] && exec <"$2" "$0" "$1"
+	[ $# -ne 1 ] && { echo $USAGE >&2; exit 1; }
+eps_file="$1"
+
+#--------------------------------------------------
+# Read Header Data
+#--------------------------------------------------
+
+while [ -z "$fields" ]
+do
+	read line
+    [ ! -t 1 ] && echo "$line"
+	[ -z "$out_basename" ] && out_basename=`expr -- "$line" : '#ANTS#PARAMS#.*out_basename{\([^}]*\)}`
+	[ -z "$run_label" ] && run_label=`expr -- "$line" : '#ANTS#PARAMS#.*run_label{\([^}]*\)}`
+	[ -z "$min_depth" ] && min_depth=`expr -- "$line" : '#ANTS#PARAMS#.*min_depth{\([^}]*\)}`
+	[ -z "$max_depth" ] && max_depth=`expr -- "$line" : '#ANTS#PARAMS#.*max_depth{\([^}]*\)}`
+	[ -z "$fields" ] && fields=`expr -- "$line" : '#ANTS#FIELDS# \(.*\)' | sed -e s/{//g -e s/}//g`
+done
+
+set -- $fields
+[ "$1" = depth -a "$4" = dc_w -a "$5" = dc_w.mad -a "$6" = dc_w.nsamp -a \
+  "${11}" = uc_w  -a "${12}" = uc_w.mad -a "${13}" = uc_w.nsamp ] || {
+		echo "$0: file layout error" >&2
+		exit 1
+}
+
+#--------------------------------------------------
+# Plot Data
+#--------------------------------------------------
+
+eps_file="$PWD/$eps_file"	# make outfile name absolute (hopefully, it is not already...)
+mkdir /tmp/$$				# GMT makes tmpfiles and is not reentrant
+cd /tmp/$$
+
+TMPFILE=/tmp/$$.LWplot_spec
+if [ ! -t 1 ]
+then
+	tee $TMPFILE
+else
+	cat > $TMPFILE
+fi
+
+[ -f .gmtdefaults4 ] ||
+	gmtset	PAPER_MEDIA letter+ \
+			LABEL_FONT_SIZE 14 ANNOT_FONT_SIZE_PRIMARY 14 \
+			WANT_EURO_FONT true \
+	        PLOT_DEGREE_FORMAT ddd:mm:ssF
+
+R=-R10/2000/1e-6/0.1
+U=-R0/1/0/1
+X=-JX10l
+
+# 1 & 3MM/S ERROR LEVELS
+err=`awk '{print $4, $1}' $TMPFILE |
+	   fillgaps -Qi linear -f '$1' '$2' |
+	   pgram -S'$2>80' -b4 -d '$2' '$1' 2>/dev/null |
+	   list -Q =1e-6/%pgram_resolution_bandwidth`
+{ echo 15 $err; echo 500 $err; } | psxy -P -X4 -K $R $X > "$eps_file"
+echo 500 $err 10 0 0 ML 1mm s@+-1@+ | pstext -O -K $R $X >> "$eps_file"
+err=`abc "9*$err"`
+{ echo 15 $err; echo 500 $err; } | psxy -O -K $R $X >> "$eps_file"
+echo 500 $err 10 0 0 ML 3mm s@+-1@+ | pstext -O -K $R $X >> "$eps_file"
+
+# EPS PARAMETERIZATION
+c1=`abc '10**(-1.754)/(4*$pi**2)'`
+l1=20; l2=1000; eps=-10;
+{ echo $l1 `abc "$c1*sqrt(1e$eps)*$l1**2"`; echo $l2 `abc "$c1*sqrt(1e$eps)*$l2**2"`; } |
+	psxy -O -K $R $X -W2/blue >> "$eps_file"
+echo `abc $l1*0.99` `abc "$c1*sqrt(1e$eps)*$l1**2"` 10 0 0 MR 10@+$eps@+ |
+	pstext -O -K $R $X -Gblue >> "$eps_file"
+echo `abc $l1*1.13` `abc "$c1*sqrt(1e$eps)*$l1**2"` 10 0 0 ML W kg@+-1@+ |
+	pstext -O -K $R $X -Gblue >> "$eps_file"
+l1=20; l2=1000; eps=-9;
+{ echo $l1 `abc "$c1*sqrt(1e$eps)*$l1**2"`; echo $l2 `abc "$c1*sqrt(1e$eps)*$l2**2"`; } |
+	psxy -O -K $R $X -W2/blue >> "$eps_file"
+echo `abc $l1*0.99` `abc "$c1*sqrt(1e$eps)*$l1**2"` 10 0 0 MR 10@+$eps@+ |
+	pstext -O -K $R $X -Gblue >> "$eps_file"
+l1=20; l2=1000; eps=-8;
+{ echo $l1 `abc "$c1*sqrt(1e$eps)*$l1**2"`; echo $l2 `abc "$c1*sqrt(1e$eps)*$l2**2"`; } |
+	psxy -O -K $R $X -W2/blue >> "$eps_file"
+echo `abc $l1*0.99` `abc "$c1*sqrt(1e$eps)*$l1**2"` 10 0 0 MR 10@+$eps@+ |
+	pstext -O -K $R $X -Gblue >> "$eps_file"
+l1=20; l2=1000; eps=-7;
+{ echo $l1 `abc "$c1*sqrt(1e$eps)*$l1**2"`; echo $l2 `abc "$c1*sqrt(1e$eps)*$l2**2"`; } |
+	psxy -O -K $R $X -W2/blue >> "$eps_file"
+echo `abc $l1*0.99` `abc "$c1*sqrt(1e$eps)*$l1**2"` 10 0 0 MR 10@+$eps@+ |
+	pstext -O -K $R $X -Gblue >> "$eps_file"
+l1=20; l2=1000; eps=-6;
+{ echo $l1 `abc "$c1*sqrt(1e$eps)*$l1**2"`; echo $l2 `abc "$c1*sqrt(1e$eps)*$l2**2"`; } |
+	psxy -O -K $R $X -W2/blue >> "$eps_file"
+echo `abc $l1*0.99` `abc "$c1*sqrt(1e$eps)*$l1**2"` 10 0 0 MR 10@+$eps@+ |
+	pstext -O -K $R $X -Gblue >> "$eps_file"
+
+# SPECTRA
+awk '{print $4, $1}' $TMPFILE |
+    fillgaps -Qi linear -f '$1' '$2' |
+	pgram -S'$2>80' -b4 -dQFT,pwrdens '$2' '$1' |
+	psxy -O -K -N -Mn $R $X -W8/coral >> "$eps_file"
+awk '{print $11,$1}' $TMPFILE |
+    fillgaps -Qi linear -f '$1' '$2' |
+	pgram -S'$2>80' -b4 -dQFT,pwrdens '$2' '$1' |
+	psxy -O -K -N -Mn $R $X -W8/SeaGreen >> "$eps_file"
+
+# LABELS
+echo 0.98 0.05 12 0 0 TR $out_basename $run_label | pstext -O -K $U -JX10/10 >> "$eps_file"
+
+psbasemap -O -K $R $X -Bf3a2:"Vertical Wavelength [m]":/f3a1:"w Power Density [m@+2@+s@+-2@+/(rad m@+-1@+)]":WeSn >> "$eps_file"
+
+rm $TMPFILE
+fixbb "$eps_file"
+
+cd "$PWD"
+rm -rf /tmp/$$
+
--- a/Sv.cpt	Sat Mar 23 13:45:31 2013 +0000
+++ b/Sv.cpt	Thu Nov 21 09:07:17 2013 -0500
@@ -1,20 +1,31 @@
+#======================================================================
+#                    S V . C P T 
+#                    doc: Wed Mar 27 18:24:12 2013
+#                    dlm: Wed Mar 27 18:26:24 2013
+#                    (c) 2013 A.M. Thurnherr
+#                    uE-Info: 28 33 NIL 0 0 72 0 2 4 NIL ofnI
+#======================================================================
+
+# HISTORY:
+#	Mar 27, 2013: - changed nan color from grey to white
+
 #ANTS# [10/19/11 ...vertical_velocity] mkCPT '-o' '--' '#-90--60:2'
 #ANTS#FIELDS# {from_z} {from_R} {from_G} {from_B} {to_z} {to_R} {to_G} {to_B} 
--90	175	0	255	-88	175	0	255
--88	96	0	255	-86	96	0	255
--86	16	0	255	-84	16	0	255
+-90	175	0	255	-88	175	0	255	L
+-88	96	0	255	-86	96	0	255	
+-86	16	0	255	-84	16	0	255	L
 -84	0	64	255	-82	0	64	255
--82	0	143	255	-80	0	143	255
+-82	0	143	255	-80	0	143	255	L
 -80	0	223	255	-78	0	223	255
--78	0	255	207	-76	0	255	207
+-78	0	255	207	-76	0	255	207	L
 -76	0	255	128	-74	0	255	128
--74	0	255	48	-72	0	255	48
+-74	0	255	48	-72	0	255	48	L
 -72	32	255	0	-70	32	255	0
--70	112	255	0	-68	112	255	0
+-70	112	255	0	-68	112	255	0	L
 -68	191	255	0	-66	191	255	0
--66	255	239	0	-64	255	239	0
+-66	255	239	0	-64	255	239	0	L
 -64	255	159	0	-62	255	159	0
--62	255	80	0	-60	255	80	0
+-62	255	80	0	-60	255	80	0	L
 B	255	0	255
 F	255	0	0
-N	127	127	127
+N	255	255	255
--- a/bottom_tracking.pl	Sat Mar 23 13:45:31 2013 +0000
+++ b/bottom_tracking.pl	Thu Nov 21 09:07:17 2013 -0500
@@ -1,9 +1,9 @@
 #======================================================================
 #                    B O T T O M _ T R A C K I N G . P L 
 #                    doc: Wed Oct 20 21:05:37 2010
-#                    dlm: Mon Oct 24 10:10:09 2011
+#                    dlm: Thu May 16 22:03:15 2013
 #                    (c) 2010 A.M. Thurnherr
-#                    uE-Info: 144 0 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 79 111 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -11,6 +11,7 @@
 #	Dec 30, 2010: - adapted for use with LADCP_w
 #	Oct 11, 2011: - moved defaults to [defaults.pl]
 #	Oct 24, 2011: - disabled not-very-useful %BT-params
+#	Apr 22, 2013: - replace output_bin_size by opt_o
 
 # This code is essentially identical to the one used in LADCPproc. Differences:
 #	1) velocity editing is simpler: no wake editing, no PPI editing, no shear
@@ -75,7 +76,8 @@
 	my($seafloor_u,$seafloor_v,$seafloor_w);
 
 	# determine which of the three trial bins is most consistent with reflr vertical velocities
-	die("assertion failed") unless numberp($LADCP{ENSEMBLE}[$ens]->{REFLR_W});
+	return													# can happen when no MEDIAN_RESIDUAL_W is available
+		unless numberp($LADCP{ENSEMBLE}[$ens]->{REFLR_W});
 	if (abs($LADCP{ENSEMBLE}[$ens]->{REFLR_W}-$w1) < abs($LADCP{ENSEMBLE}[$ens]->{REFLR_W}-$w2) &&
 		abs($LADCP{ENSEMBLE}[$ens]->{REFLR_W}-$w1) < abs($LADCP{ENSEMBLE}[$ens]->{REFLR_W}-$w3)) {
 			$seafloor_u = $LADCP{ENSEMBLE}[$ens]->{U_UNEDITED}[$seafloor_bin-1];
@@ -103,7 +105,7 @@
 
 	for (my($bin)=$LADCP_firstBin-1; $bin<=$LADCP_lastBin-1; $bin++) {
 		next unless defined($LADCP{ENSEMBLE}[$ens]->{W}[$bin]);
-		my($gi) = int($bd[$bin]) / $output_bin_size;
+		my($gi) = int($bd[$bin]) / $opt_o;
 		push(@{$BTw[$gi]},$LADCP{ENSEMBLE}[$ens]->{W}[$bin]-$seafloor_w);
 	}
 }
--- a/defaults.pl	Sat Mar 23 13:45:31 2013 +0000
+++ b/defaults.pl	Thu Nov 21 09:07:17 2013 -0500
@@ -1,9 +1,9 @@
 #======================================================================
 #                    D E F A U L T S . P L 
 #                    doc: Tue Oct 11 17:11:21 2011
-#                    dlm: Mon Oct 15 21:34:00 2012
+#                    dlm: Thu Sep  5 22:46:45 2013
 #                    (c) 2011 A.M. Thurnherr
-#                    uE-Info: 26 14 NIL 0 0 72 0 2 4 NIL ofnI
+#                    uE-Info: 37 55 NIL 0 0 72 0 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -25,6 +25,16 @@
 #	Oct 11, 2012: - added .TL output to defaults
 #--- hg commit
 #	Oct 15, 2012: - removed support for TLhist
+#	Apr 22, 2013: - removed option variable aliases
+#	May 14, 2013: - opt_m => w_max_lim
+#				  - BUG: default processing params file was still .default
+#	May 15, 2013: - changed default profile plot to show 2-beam solutions
+#				  - BUG: out_TLhist entry was still there
+#	May 16, 2013: - -a => -d
+#	Jun  5, 2013: - renamed $discard_data_from_beam to $bad_beam
+#	Jun  5, 2013: - made ProcessingParams (without .profiles) default file
+#	Sep  5, 2013: - also allow ProcessingParams.default
+#				  - added LWplot_spec to default output
 
 # Variable Names:
 #	- variables that are only used in a particular library are
@@ -40,22 +50,22 @@
 	$processing_param_file = "ProcessingParams.$RUN";
 } elsif (-r "ProcessingParams.default") {
 	$processing_param_file = "ProcessingParams.default";
+} elsif (-r "ProcessingParams") {
+	$processing_param_file = "ProcessingParams";
 } else {
-	croak("$0: cannot load either <ProcessingParams.$RUN> or <ProcessingParams.default>\n");
+	croak("$0: cannot find either <ProcessingParams.$RUN> or <ProcessingParams[.default]>\n");
 }
 
-
 # CTD depth adjustment
-#	- set with -a
+#	- set with -d (-a up to 2013/05/16)
 #	- value is added to CTD pressure
 #	- use when CTD has -ve pressures
 
-$CTD_neg_press_offset = &antsFloatOpt($opt_a,0);
-
+&antsFloatOpt(\$opt_d,0);
 
 # suppress 3-beam LADCP solutions
 
-$RDI_Coords::minValidVels = 4 if ($opt_4);							
+#$opt_4 = 1;
 
 
 # correct attiude sensors
@@ -68,10 +78,6 @@
 #	- defaults to 2-last
 
 $opt_b = '2,*' unless defined($opt_b);
-($LADCP_firstBin,$LADCP_lastBin) = split(',',$opt_b);
-croak("$0: cannot decode -b $opt_b\n")
-    unless (numberp($LADCP_firstBin) &&
-            ($LADCP_lastBin eq '*' || numberp($LADCP_lastBin)));
 
 #======================================================================
 # Logging and Output
@@ -79,22 +85,22 @@
 
 #	- there are 4 verbosity levels, selected by -v
 #		0:	only print errors
-#		1:	default, UNIX-like (warnings and info messages that are not produced for every cast)
-#		2:	progress messages and useful information
+#		1:	UNIX-like (warnings and info messages that are not produced for every cast)
+#		2:	(default) progress messages and useful information
 #		>2:	debug messges
 #	- the most useful ones of these are 1 & 2
 
-$verbosity_level = &antsCardOpt($opt_v,2);
+&antsCardOpt(\$opt_v,2);
 
 
 # output bin size in meters
 
-$output_bin_size = &antsFloatOpt($opt_o,10);
+&antsFloatOpt(\$opt_o,10);
 
 
 # min w samples required for each vertical-velocity bin
 
-$min_w_nsamp = &antsCardOpt($opt_k,20);
+&antsCardOpt(\$opt_k,20);
 
 
 # output base name
@@ -112,18 +118,19 @@
 #	_w.eps			vertical velocities
 #	_residuals.eps	residual vertical velocities
 #	_Sv.eps			volume scattering coefficient after Deimes (1999)
-#	_corr.eps		correlation
+#	_corr.eps		correlation [DISABLED 2013/05/16]
 
 $out_w = "| LWplot_residuals $plot_subdir/${out_basename}_residuals.eps" .
 		 "| LWplot_Sv $plot_subdir/${out_basename}_Sv.eps" .
-		 "| LWplot_corr $plot_subdir/${out_basename}_corr.eps" .
+#		 "| LWplot_corr $plot_subdir/${out_basename}_corr.eps" .
 		 "| LWplot_w $plot_subdir/${out_basename}_w.eps" .
 		 "> $data_subdir/$out_basename.w";
 
 
 # w profile output
 
-$out_profile = "| LWplot_prof $plot_subdir/${out_basename}_prof.eps" .
+$out_profile = "| LWplot_prof_2beam $plot_subdir/${out_basename}_prof.eps" .
+			   "| LWplot_spec $plot_subdir/${out_basename}_spec.eps" .
 			   "> $data_subdir/$out_basename.prof";
 
 # log output
@@ -131,18 +138,21 @@
 $out_log = "$log_subdir/$out_basename.log";
 
 
-# time-series output
+# time-series output (CTD acceleration effect)
 
-$out_timeseries = "$data_subdir/$out_basename.tis";
+$out_timeseries = "| LWplot_CAE $plot_subdir/${out_basename}_CAE.eps" .
+				  "> $data_subdir/$out_basename.tis";
 
 
-# diagnostic plots
+# per-bin residual output (plot only)
+
+$out_BR		= "| LWplot_BR $plot_subdir/${out_basename}_BR.eps";
+
 
-$out_BR		= "| LWplot_BR 	   $plot_subdir/${out_basename}_BR.eps";
-$out_TL 	= "| LWplot_TL     $plot_subdir/${out_basename}_TL.eps" .
+# time-lagging output
+
+$out_TL 	= "| LWplot_TL $plot_subdir/${out_basename}_TL.eps" .
 			  "> $data_subdir/$out_basename.TL";
-$out_TLhist = "| LWplot_TLhist $plot_subdir/${out_basename}_TLhist.eps";
-
 
 #======================================================================
 # Data Editing
@@ -150,17 +160,17 @@
 
 # min correlation
 
-$min_correlation = &antsFloatOpt($opt_c,70);
+&antsFloatOpt(\$opt_c,70);
 
 
 # max tilt (pitch/roll)
 
-$max_tilt = &antsFloatOpt($opt_t,15);
+&antsFloatOpt(\$opt_t,15);
 
 
 # max err vel
 
-$max_allowed_errvel = &antsFloatOpt($opt_e,0.1);
+&antsFloatOpt(\$opt_e,0.1);
 
 
 # truncate farthest valid velocities
@@ -170,17 +180,17 @@
 
 # discard velocities from chosen beam (1-4)
 
-$discard_velocities_from_beam = 0;
+$bad_beam = 0;
 
 
 # max LADCP gap length in seconds
 
-$max_LADCP_reflr_vel_gap = &antsFloatOpt($opt_g,60);
+&antsFloatOpt(\$opt_g,60);
 
 
 # max allowed vertical velocity in m/s
 
-$max_allowed_w = &antsFloatOpt($opt_m,1);
+$w_max_lim = 1;
 
 
 # in each ensemble, vertical velocities differing more than this
@@ -209,7 +219,7 @@
 
 # externally supplied lag
 
-$first_guess_timelag = $opt_i;
+# $opt_i = 567;
 
 
 # reference layer bins for w for time matching
@@ -220,18 +230,12 @@
 # number of time lags during each of 2 lagging steps
 
 $opt_n = '10,100' unless defined($opt_n);
-@number_of_timelag_windows = split(',',$opt_n);
-croak("$0: cannot decode -n $opt_n\n")
-	unless numberp($number_of_timelag_windows[0]) && numberp($number_of_timelag_windows[1]);
 
 
 # time lag search window widths for each of 2 lagging steps
 #	- full width in seconds
 
 $opt_w = '240,20' unless defined($opt_w);
-@length_of_timelag_windows = split(',',$opt_w);
-croak("$0: cannot decode -w $opt_w\n")
-	unless numberp($length_of_timelag_windows[0]) && numberp($length_of_timelag_windows[1]);
 
 
 # if top 3 lags have spread greater than $TL_max_allowed_three_lag_spread
@@ -243,7 +247,7 @@
 # 	- the optimum value of $TL_max_allowed_three_lag_spread may be cast-duration dependent
 
 $TL_max_allowed_three_lag_spread = 3;
-$TL_required_top_three_fraction = &antsFloatOpt($opt_3,0.6);
+&antsFloatOpt(\$opt_3,0.6);
 
 
 #======================================================================
--- a/edit_data.pl	Sat Mar 23 13:45:31 2013 +0000
+++ b/edit_data.pl	Thu Nov 21 09:07:17 2013 -0500
@@ -1,9 +1,9 @@
 #======================================================================
 #                    E D I T _ D A T A . P L 
 #                    doc: Sat May 22 21:35:55 2010
-#                    dlm: Mon Oct 15 10:03:13 2012
+#                    dlm: Tue Nov 12 03:09:49 2013
 #                    (c) 2010 A.M. Thurnherr
-#                    uE-Info: 28 81 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 33 29 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -26,8 +26,11 @@
 #	Oct 27, 2011: - adapted editTilt() to new call location
 #				  - added correctAttitude()
 #	Oct 15, 2012: - BUG: editSurfLayer() counted also ensembles without CTD depth
+#	Nov 12, 2013: - added comments on editCorr_Earthcoords()
 
 # NOTES:
+#	- editCorr_Earthcoords() is overly conservative and removed most
+#	  or all 3-beam solutions
 #	- all bins must be edited (not just the ones between $LADCP_firstBin
 #	  and $LADCP_lastBin to allow reflr calculations to use bins outside
 #	  this range (ONLY FOR BEAM-COORD EDITS)
@@ -87,6 +90,18 @@
 	return $nrm;
 }
 
+#======================================================================
+# $removed = editCorr_Earthcoords($ens,$threshold)
+#
+# NOTES:
+#	- if any of the 4 beam correlations is below the threshold,
+#	  the entire velocity is removed
+#	- this implies that (most? all?) three-beam solutions will
+#	  be edited out, which is overly conserative
+#	- a potentially better algorithm (used in LADCPproc) ignores the
+#	  lowest correlation in all 3-beam solutions
+#======================================================================
+
 sub editCorr_Earthcoords($$)
 {
 	my($ens,$lim) = @_;
--- a/time_lag.pl	Sat Mar 23 13:45:31 2013 +0000
+++ b/time_lag.pl	Thu Nov 21 09:07:17 2013 -0500
@@ -1,9 +1,9 @@
 #======================================================================
 #                    T I M E _ L A G . P L 
 #                    doc: Fri Dec 17 21:59:07 2010
-#                    dlm: Tue Oct 16 20:13:38 2012
+#                    dlm: Sat May 18 11:35:50 2013
 #                    (c) 2010 A.M. Thurnherr
-#                    uE-Info: 288 0 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 60 15 NIL 0 0 72 0 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -47,6 +47,9 @@
 #				  - removed support for TLhist
 #	Oct 16, 2012: - renamed field elapsed to elapsed.LADCP for clarity
 #				  - made failure "soft"
+#	Mar 23, 2012: - adapted to piece-wise time lagging
+#	Apr 22, 2013: - replaced $max_allowed_w by $opt_m, $TL_required_top_three_fraction by $opt_3
+#	May 14, 2013: - opt_m => w_max_lim
 
 # DIFFICULT STATIONS:
 #	NBP0901#131		this requires the search-radius doubling heuristic
@@ -54,6 +57,8 @@
 # TODO:
 #	- better seabed code (from LADCPproc)
 
+my($TINY) = 1e-6;
+
 sub mad_w($$$)									# mean absolute deviation
 {
 	my($fe,$le,$so) = @_;						# first/last LADCP ens, CTD scan offset
@@ -65,10 +70,10 @@
 		die("assertion failed\n" .
 			"\ttest: abs($LADCP{ENSEMBLE}[$e]->{ELAPSED} + $CTD{TIME_LAG} - $CTD{ELAPSED}[$s]) <= $CTD{DT}/2\n" .
 			"\te = $e, s = $s, ensemble = $LADCP{ENSEMBLE}[$e]->{NUMBER}"
-		) unless (abs($LADCP{ENSEMBLE}[$e]->{ELAPSED} + $CTD{TIME_LAG} - $CTD{ELAPSED}[$s]) <= $CTD{DT}/2);
+		) unless (abs($LADCP{ENSEMBLE}[$e]->{ELAPSED} + $CTD{TIME_LAG} - $CTD{ELAPSED}[$s]) <= $CTD{DT}/2+$TINY);
 		next unless numberp($LADCP{ENSEMBLE}[$e]->{REFLR_W});
 		my($dw) = $LADCP{ENSEMBLE}[$e]->{REFLR_W}-$LADCP_mean_w - ($CTD{W}[$s+$so]-$CTD_mean_w);
-		next unless (abs($dw) <= $max_allowed_w);
+		next unless (abs($dw) <= $w_max_lim);
 
 		$LADCP_mean_w += $LADCP{ENSEMBLE}[$e]->{REFLR_W};
 		$CTD_mean_w   += $CTD{W}[$s+$so];
@@ -82,7 +87,7 @@
 		my($s) = int(($LADCP{ENSEMBLE}[$e]->{ELAPSED} + $CTD{TIME_LAG} - $CTD{ELAPSED}[0]) / $CTD{DT} + 0.5);
 		my($dw) = $LADCP{ENSEMBLE}[$e]->{REFLR_W}-$LADCP_mean_w - ($CTD{W}[$s+$so]-$CTD_mean_w);
 		next unless numberp($LADCP{ENSEMBLE}[$e]->{REFLR_W});
-		next unless (abs($dw) <= $max_allowed_w);
+		next unless (abs($dw) <= $w_max_lim);
 		$sad += abs($dw);
 		$n++;
 	}
@@ -116,17 +121,16 @@
 
 { # STATIC SCOPE
 
-my(@dc_elapsed,@dc_so,@dc_mad);								# buffer 
+my(@elapsed_buf,@so_buf,@mad_buf,@bmo_buf,@te_buf,$elapsed_min_buf);	
 
-sub calc_lag($$$$)
+sub calc_lag($$$$$)
 {
-	my($n_windows,$w_size,$scan_increment,$cast_type) = @_;
+	my($n_windows,$w_size,$scan_increment,$first_ens,$last_ens) = @_;
 	my($search_radius) = $scan_increment==1 ? 3 : $w_size;
 
 	my($ctmsg);
-	if ($cast_type == 0) 	{ $ctmsg = "full-cast"; }
-	elsif ($cast_type == 1) { $ctmsg = "down-cast"; }
-	else 					{ $ctmsg = "up-cast"; }
+	if ($first_ens==$firstGoodEns && $last_ens==$lastGoodEns) 	{ $ctmsg = "full-cast"; }
+	else														{ $ctmsg = "partial-cast"; }
 
 RETRY:
 	my($failed) = undef;
@@ -148,19 +152,11 @@
 	my(@elapsed,@so,@mad,%nBest,%madBest);
 	my($n_valid_windows) = 0;
 
-	my($first_ens,$last_ens);
-	if ($cast_type == 0) {													# dc/uc
-		$first_ens = $approx_joint_profile_start_ens;
-		$last_ens  = $approx_joint_profile_end_ens;
-	} elsif ($cast_type == 1) {												# dc
-		$first_ens = $approx_joint_profile_start_ens;
-		$last_ens  = $LADCP_atbottom;
-	} elsif ($cast_type == -1) {											# uc
-		$first_ens = $LADCP_atbottom;
-		$last_ens  = $approx_joint_profile_end_ens;
-	} else {
-		croak("$0: illegal \$cast_type");
-	}
+	$first_ens = $approx_joint_profile_start_ens
+		if ($first_ens < $approx_joint_profile_start_ens); 
+	my($last_lag_piece) = ($last_ens == $lastGoodEns);							# none is following
+	$last_ens = $approx_joint_profile_end_ens
+		if ($last_ens > $approx_joint_profile_end_ens);
 
 	for (my($wi)=0; $wi<$n_windows; $wi++) {
 		my($fe) = $first_ens + int(($last_ens-$first_ens-$window_ens)*$wi/($n_windows-1)+0.5);
@@ -210,7 +206,7 @@
 			$best_lag[0],int(($nBest{$best_lag[0]}/$n_valid_windows)*100+0.5),100*$madBest{$best_lag[0]});
 	}
 
-	unless ($nBest{$best_lag[0]}+$nBest{$best_lag[1]}+$nBest{$best_lag[2]} >= $TL_required_top_three_fraction*$n_valid_windows) {
+	unless ($nBest{$best_lag[0]}+$nBest{$best_lag[1]}+$nBest{$best_lag[2]} >= $opt_3*$n_valid_windows) {
 		if (max(@best_lag)-min(@best_lag) > $TL_max_allowed_three_lag_spread) {
 			warning(2,"$0: cannot determine a valid $ctmsg lag; top 3 tags account for %d%% of total (use -3 to relax criterion)\n",
 				int(100*($nBest{$best_lag[0]}+$nBest{$best_lag[1]}+$nBest{$best_lag[2]})/$n_valid_windows+0.5));
@@ -251,33 +247,28 @@
 	if (defined($out_TL) && $scan_increment==1) {
 		progress("\tsaving/plotting time-lagging time series...\n");
 	
-		if ($cast_type == 1) {				# dc => buffer data in static scope. output will be produced during uc
-			@dc_elapsed = @elapsed; @dc_so = @so; @dc_mad = @mad;
-			$dc_elapsed_min = $elapsed[0]; $dc_bmo = $bmo;
-		} else {							# uc or duc
+		push(@elapsed_buf,@elapsed);								# buffer elapsed data in static scope
+		push(@so_buf,@so);											# scan offset
+		push(@mad_buf,@mad);										# mean absolute deviation
+		push(@bmo_buf,$bmo);										# best median offset
+		push(@te_buf,$elapsed[$#elapsed]);							# to elapsed (from elapsed to elapsed, capisc?)
+		$elapsed_min_buf = $elapsed[0]								# min of valid elapsed (for plotting)
+			unless defined($elapsed_min_buf);
+
+		if ($last_lag_piece) {										# output all data
 			my($saveParams) = $antsCurParams;
 			@antsNewLayout = ('elapsed.LADCP','scan_offset','mad','downcast');
 			open(STDOUT,"$out_TL") || croak("$out_TL: $!\n");
 	
-			if ($cast_type == -1) {			# uc => first output buffered dc data
-				&antsAddParams('best_scan_offset.dc',$dc_bmo);
-				&antsAddParams('best_scan_offset.uc',$bmo);
-				&antsAddParams('elapsed.min',$dc_elapsed_min);
-				&antsAddParams('elapsed.max',$elapsed[$#elapsed]);
-				&antsAddParams('elapsed.bot',$elapsed[0]);
-				for (my($wi)=0; $wi<@dc_elapsed; $wi++) {
-					&antsOut($dc_elapsed[$wi],$dc_so[$wi],$dc_mad[$wi],1);
-				}
-				for (my($wi)=0; $wi<@elapsed; $wi++) {
-					&antsOut($elapsed[$wi],$so[$wi],$mad[$wi],0);
-				}
-			} else {						# duc (not used as of 10/15/2012, but should work with adaptation of [LWplot_TL]
-				&antsAddParams('best_scan_offset',$bmo);
-				&antsAddParams('elapsed.min',$elapsed[0]);
-				&antsAddParams('elapsed.max',$elapsed[$#elapsed]);
-				for (my($wi)=0; $wi<@elapsed; $wi++) {
-					&antsOut($elapsed[$wi],$so[$wi],$mad[$wi],$elapsed[$wi]<$LADCP{ENSEMBLE}[$LADCP_atbottom]->{ELAPSED});
-				}
+			&antsAddParams('best_scan_offsets',"@bmo_buf");
+			&antsAddParams('to_elapsed_limits',"@te_buf");
+			&antsAddParams('elapsed.min',$elapsed_min_buf);
+			&antsAddParams('elapsed.max',$elapsed_buf[$#elapsed_buf]);
+			&antsAddParams('elapsed.bot',$LADCP{ENSEMBLE}[$LADCP_atbottom]->{ELAPSED});
+
+			for (my($wi)=0; $wi<@elapsed_buf; $wi++) {
+				&antsOut($elapsed_buf[$wi],$so_buf[$wi],$mad_buf[$wi],
+							($elapsed_buf[$wi]<$LADCP{ENSEMBLE}[$LADCP_atbottom]->{ELAPSED}));
 			}
 	
 			&antsOut('EOF'); open(STDOUT,">&2");
--- a/time_series.pl	Sat Mar 23 13:45:31 2013 +0000
+++ b/time_series.pl	Thu Nov 21 09:07:17 2013 -0500
@@ -1,9 +1,9 @@
 #======================================================================
 #                    T I M E _ S E R I E S . P L 
 #                    doc: Sun May 23 16:40:53 2010
-#                    dlm: Wed Oct 12 12:36:46 2011
+#                    dlm: Wed Apr 17 17:05:16 2013
 #                    (c) 2010 A.M. Thurnherr
-#                    uE-Info: 102 23 NIL 0 0 72 2 2 4 NIL ofnI
+#                    uE-Info: 20 63 NIL 0 0 72 2 2 4 NIL ofnI
 #======================================================================
 
 # HISTORY:
@@ -17,6 +17,7 @@
 #	Oct 11, 2011: - BUG: {DEPTH} had not been set at start of profile
 #	Oct 12, 2011: - re-worked ref_lr_w()
 #				  - stopped depth integration across gaps >= 5s
+#	Apr 17, 2013: - improved gap message (added ensemble range)
 
 # NOTES:
 #	- resulting DEPTH field based on integrated w without any sound speed correction
@@ -90,10 +91,10 @@
 				next;
 			}
 			if ($dta->{ENSEMBLE}[$e]->{ELAPSED} < 200) {
-				warning(1,"long gap (%ds) at ensemble #$dta->{ENSEMBLE}[$e]->{NUMBER}, %ds into the profile\n",
+				warning(1,"long gap (%ds) at ensembles #$dta->{ENSEMBLE}[$lastgood]->{NUMBER}-$dta->{ENSEMBLE}[$e]->{NUMBER}, %ds into the profile\n",
 					$dt,$dta->{ENSEMBLE}[$e]->{ELAPSED});
 			} else {
-				warning(1,"long gap (%ds) at ensemble #$dta->{ENSEMBLE}[$e]->{NUMBER}, %.1fmin into the profile\n",
+				warning(1,"long gap (%ds) at ensembles #$dta->{ENSEMBLE}[$lastgood]->{NUMBER}-$dta->{ENSEMBLE}[$e]->{NUMBER}, %.1fmin into the profile\n",
 					$dt,$dta->{ENSEMBLE}[$e]->{ELAPSED}/60);
 			}
 		}
--- a/w.cpt	Sat Mar 23 13:45:31 2013 +0000
+++ b/w.cpt	Thu Nov 21 09:07:17 2013 -0500
@@ -1,16 +1,24 @@
+#======================================================================
+#                    W . C P T 
+#                    doc: Wed Mar 27 18:32:37 2013
+#                    dlm: Wed Mar 27 18:38:51 2013
+#                    (c) 2013 A.M. Thurnherr
+#                    uE-Info: 21 41 NIL 0 0 72 0 2 4 NIL ofnI
+#======================================================================
+
 #ANTS# [10/15/11 ...vertical_velocity] mkCPT '-oc' 'polar' '--' '-0.07' '-0.05' '-0.04' '-0.03' '-0.02' '-0.01' '0.01' '0.02' '0.03' '0.04' '0.05' '0.07'
 #ANTS#FIELDS# {from_z} {from_R} {from_G} {from_B} {to_z} {to_R} {to_G} {to_B} 
--0.07	64	64	255	-0.05	64	64	255
--0.05	112	112	255	-0.04	112	112	255
--0.04	143	143	255	-0.03	143	143	255
--0.03	175	175	255	-0.02	175	175	255
--0.02	207	207	255	-0.01	207	207	255
--0.01	255	255	255	0.01	255	255	255
-0.01	255	207	207	0.02	255	207	207
-0.02	255	175	175	0.03	255	175	175
-0.03	255	143	143	0.04	255	143	143
-0.04	255	112	112	0.05	255	112	112
-0.05	255	64	64	0.07	255	64	64
+-0.07	64	64	255	-0.05	64	64	255	B
+-0.05	112	112	255	-0.04	112	112	255 L
+-0.04	143	143	255	-0.03	143	143	255	
+-0.03	175	175	255	-0.02	175	175	255 L
+-0.02	207	207	255	-0.01	207	207	255 
+-0.01	255	255	255	0.01	255	255	255 L
+0.01	255	207	207	0.02	255	207	207 L
+0.02	255	175	175	0.03	255	175	175	
+0.03	255	143	143	0.04	255	143	143	L
+0.04	255	112	112	0.05	255	112	112 
+0.05	255	64	64	0.07	255	64	64	B
 B	0	0	255
 F	255	0	0
 N	127	127	127