function orca_opt_write(opt_root,iicomm,type_opts,gen_opts,cw_freqs,cw_opts,zs_lims,zr_lims,rng_lims, ...
	zmf_lims,bb_parms,bb_opts,var_parm1,var_parm2,kpl_parms,rc_parms);
%
% Call orca_opt_write(opt_root,iicomm,type_opts,gen_opts,cw_freqs,cw_opts,zs_lims,zr_lims,rng_lims, ...
%	zmf_lims,bb_parms,bb_opts,var_parm1,var_parm2,kpl_parms,rc_parms)
%
% Outputs ORCA option file named [opt_root,'.opt'];
%
% iicomm		= 0 for no comment lines in OPT file, 1=to include comment lines in OPT file;
% type_opts		= [iicw,iikpl,iirc,iiparm,n_env];
% gen_opts		= [iirx,cphmin,cphmax,rmin rmax,phfac,db_cut,Aih_l,Aih_u,kkblm,iigbs,iidiag]
% cw_freqs		= [nfreq f1 f2 ...] or [-nfreq fmin fmax];
% cw_opts		= [iitl,iimf,iisig,iimt,iidc,iikn,iieig,iikrak,iioas,iifepe,iimlab, ...
%                 iitl_coh,iitl_ph,iimf_dphi,iimf_im];
% zs_lims		= Source depths [zs1;zs2;...], [zsmin,zsmax,nzs], OR [zsmin,zsmax,-dzs] in m [CW & BB];
% zr_lims		= Receiver depths [zr1;zr2;...], [zrmin,zrmax,nzr], OR [zrmin,zrmax,-dzr] in m [CW & BB];
%               OR character array of array geometry file;
% rng_lims		= Ranges [rng1;rng2;...], [rngmin,rngmax,nrng], OR [rngmin,rngmax,-drng] in km [CW & BB];
% zmf_lims		= Mode function depths [zmf1; zmf2; ...], [zmfmin,zmfmax,nzmf], OR [zmfmin,zmfmax,-dzmf] in m;
% bb_parms		= Broadband parms: [fs,+nfft/-Tw,fmin,fmax];
% bb_opts		= Broadband options: [iifft,iiout,iift,iimt,iidc,iimf];
% var_parm1		= Parameter variation: [nrun,nparm];
% var_parm2		= Parameter variation: [obt,nlay,ktb,pc,val1,val2] (nparm rows);
% kpl_parms		= k-Plane Image parms: [freq,iivar,iikf,kr1,kr2,nkr,ki1,ki2,nki,nduct,iiph,iishp,iishs];
% rc_parms		= 2-element cell array giving Reflection Coeff parms for iirc=1: 
%                 {1}=[freq1,freq2,+nfreq/-dfreq] or [freq1;freq2; ...]
%                 {2}=[theta1,theta2,+ntheta/-dtheta] or [theta1;theta2; ...]
%
% if ischar(zr_lims), 
% 	[rec_xyz,cavg,nph,iif]=arr_geom(zr_lims);
%     zr=rec_xyz(:,3);
%     if ~all(rec_xyz(:,1)==rec_xyz(1,1) & rec_xyz(:,2)==rec_xyz(1,2)),
%         error('USER ERROR: Array geometry file can only be a VLA at this time!!');
%     end
%     if ~iif, error(['USER ERROR: Could not find array geometry file = ',zr_lims]); end
% else, 
%     zr=zr_lims;
% end
%if size(rec_xyz,2)~=3, error('USER ERROR: rec_xyz must be [nph,3] array of receiver x,y,z positions'); end
%
%
% COPYRIGHT (c) 2008
% 
% Applied Research Laboratories, The University of Texas at Austin
% (ARL:UT)
% All rights reserved.
% 
% This material may be reproduced by or for the U.S. Government
% only. This notice must appear in all copies of this file and its
% derivatives. Further distribution outside the U.S. Government is
% prohibited without the explicit written authorization from the
% Director of the Environmental Sciences Laboratory, ARL:UT.
% 
% THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
% EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE
% IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
% PURPOSE, OR NONINFRINGEMENT.
% 
% IN NO EVENT WILL ARL:UT BE LIABLE FOR ANY DAMAGES WHATSOEVER ARISING
% OUT OF THE USE OR INABILITY TO USE THIS SOFTWARE, EVEN IF ARL:UT HAS
% BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
zr=zr_lims;
%
opt_file=[opt_root,'.opt'];
fid_out=fopen(opt_file,'w');
if fid_out < 0,
	error(sprintf(['\nERROR: OPT FILE %s COULD NOT BE OPENED FOR WRITING.\n', ...
         'CHECK THAT IT IS NOT BEING EDITED'],opt_file));
end
%
iicw=type_opts(1); iikpl=type_opts(2); iirc=type_opts(3); iiparm=type_opts(4);
rmin=gen_opts(4);
iitl=cw_opts(1); iisig=cw_opts(3); iidc=cw_opts(5); iikn=cw_opts(6); iieig=cw_opts(7);
if iitl & cw_opts(12), iitl=3; end               % Incoherent TL also;
if iitl & cw_opts(13), iitl=-iitl; end                 % Phase also;
iimf=cw_opts(2); iirx=gen_opts(1); 
if iicw==2, iirx=2*iirx; end        % For Real Axis broadband, use brute force approach;
if iicw==1 & rmin==0 & iitl==0,
    error(sprintf(['\nUSER ERROR: For CW with rmin=0, must have iitl ranges to supply rmin.\n', ...
          'Set rmin>0 or specify TL ranges.']));
end
iifft=bb_opts(1);
if iicw==2 & rmin==0 & iifft==0,
    error(sprintf(['\nUSER ERROR: For Broadband with rmin=0, must have iifft ranges to supply rmin.\n', ...
          'Set rmin>0 or specify FFT ranges.']));
end
iimf=(iicw==1 & cw_opts(2)) | (iicw==2 & bb_opts(6));
%
if iicw==1 & ~any([iitl,iimf,iisig,iidc,iikn,iieig]),
    error(sprintf(['\nUSER ERROR: ORCA not called because no outputs requested for iicw=1 (CW calcuations).\n', ...
          'Select outputs such as TL, mode functions, eigenvalues and run again.']));
end
if iicw==2 & ~any(bb_opts),
    error(sprintf(['\nUSER ERROR: ORCA not called because no outputs requested for iicw=2 (broadband calculations).\n', ...
          'Select outputs such as FFT file, mode functions, or group velocity and run again.']));
end
%
if iicomm,
	fprintf(fid_out,'               ### OPTION FILE FOR ORCA NORMAL MODE MODEL ###\n');
	fprintf(fid_out,'          ### ENTER DATA AFTER LINES WITH * IN FIRST COLUMN ###\n');
	fprintf(fid_out,'                  ### USE OTHER LINES FOR COMMENTS ###\n');
	fprintf(fid_out,'==> TYPE(S) OF COMPUTATIONS DESIRED:\n');
	fprintf(fid_out,'ver_no = Version Number of Option File (DO NOT CHANGE THIS);\n');
	fprintf(fid_out,'iicw   = Mode Computations (0=no; 1=CW; 2=Broadband);\n');
	fprintf(fid_out,'iikpl  = Complex k-Plane Images [0=no; 1=ln(R1*R2); 2=ln(1-R1*R2)];\n');
	fprintf(fid_out,'iirc   = PW Reflection Coeff (0=no; 1=R vs angle,f; 2=FFT file vs. angle);\n');
	fprintf(fid_out,'iiparm = Parameter Study Using iicw,iikpl,iirc above (0=no; 1=yes);\n');
	fprintf(fid_out,'n_env  = Geoacoustic Profile (_prof) Output File (0=no; pos=# depth pts);\n');
	fprintf(fid_out,'iifmt  = Output Format (1=HDF;2=MAT;3=ASCII;0=all);\n');
end
%
fprintf(fid_out,'*(1) ver_no  iicw  iikpl  iirc  iiparm  n_env  iifmt\n');
fprintf(fid_out,'       2.10 %5i  %5i  %4i  %6i  %5i      1\n',type_opts);
%                       2.10     1      0     0       0      0      1
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'==> MODE COMPUTATION GENERAL PARAMETERS (iicw>0 on Line 1):\n');
	fprintf(fid_out,'    SET ALL TO 0 TO FIND MODES AUTOMATICALLY\n');
	fprintf(fid_out,'iirx   = Real axis version (0=no, 1=yes);\n');
	fprintf(fid_out,'cphmin = Min Phase Speed (0=p-wave modes only; -1=seismic modes also);\n');
	fprintf(fid_out,'cphmax = Max Phase Speed [0=use rmin; pos=speed; neg=max angle(deg)];\n');
	fprintf(fid_out,'rmin   = Min Range of Interest in km [>999=use cphmax; 0=use S/R geom];\n');
	fprintf(fid_out,'rmax   = Max Range of Interest in km (0=use S/R geom);\n');
	fprintf(fid_out,'phfac  = Phase Step Parm: Step by 2*pi/phfac (set to 4-8, 0=default==>4);\n');
	fprintf(fid_out,'db_cut = Modes Weaker By db_cut Ignored (set to 30-60, 0=default==>50);\n');
	fprintf(fid_out,'Aih_l  = Gradient lower h-space: 0=default,-1=homogeneous, >0=da_bar;\n');
	fprintf(fid_out,'Aih_u  = Gradient lower h-space: 0=default,-1=homogeneous, >0=da_bar;\n');
	fprintf(fid_out,'kkblm  = Set to 1 to search for branch line modes;\n');
	fprintf(fid_out,'iigbs  = Gaussian Beam Source (0=no,1=yes) [iirx=0 only; add beam angle\n');
	fprintf(fid_out,'         and beamwidth for each source depth in lines (5) or (8)];\n');
	fprintf(fid_out,'iidiag = Print Diagnostic Msgs;\n');
end
fprintf(fid_out,'*(2) iirx cphmin cphmax rmin rmax phfac db_cut Aih_l Aih_u kkblm iigbs iidiag\n');
fprintf(fid_out,'%6i %6.0f %7.1f %5.3f %5.0f %5i %6i %5i %5i %5i %5i %6i\n',gen_opts);
%        0      0      0    0    0     4     40 90.005  -1     0     0      0
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'CW MODE PARAMETERS ON NEXT 5 LINES (iicw=1 on Line 1)\n');
	fprintf(fid_out,'Frequencies (nf>0 ==> List f''s; nf<0 ==> List first,last f):\n');
end
fprintf(fid_out,'*(3) nf f1 f2 ...\n');
if iicw==1 | iiparm==1,
	orca_lim_out(fid_out,cw_freqs,'cw_freqs','%6.1f');
end
%
if iicomm,
	fprintf(fid_out,'---------------------------------------------------------------------------\n');
	fprintf(fid_out,'CW Mode Output Options:\n');
	fprintf(fid_out,'iitl  = TL (0=no;1=zs,zr,r on Line 5; 2=src track/rec array on Line 10)\n');
	fprintf(fid_out,'iimf  = Mode Functions (0=no,1=p-wave,2=s-wave,3=both). Enter depths on Line 6.\n');
	fprintf(fid_out,'iisig = Disp uz,ux and Stress sigzz,sigzx (0=no,1=yes). Enter depths on Line 6.\n');
	fprintf(fid_out,'iimt  = Mode Trajectory in k-plane (ASCII file).\n');
	fprintf(fid_out,'iidc  = Disp Curves(0=no,1=vg,2=vph,3=both);\n');
	fprintf(fid_out,'iikn  = Mode Eigenvalues Re(kn),Im(kn);\n');
	fprintf(fid_out,'iieig = List of eigenvalue characteristics;\n');
	fprintf(fid_out,'iikrak,iioas,iifepe,iimlab = Output Kraken, OASES, FEPE, MODELAB input files;\n');
end
fprintf(fid_out,'*(4) iitl iimf iisig iimt iidc iikn iieig iikrak iioas iifepe iimlab\n');
%if iicw==1 | iiparm==1,
if length(cw_opts)~=16,
    disp(cw_opts);
	error(['USER ERROR: cw_opts must be [iitl,iimf,iisig,iimt,iidc,iikn,iieig,iikrak,iioas,', ...
	    'iifepe,iimlab,iitl_inc,iitl_ph,iimf_re,iimf_im](15 long).']); 
end
if cw_opts(2) & cw_opts(16), iimf=4, end       % dphi also;
fprintf(fid_out,'%9i %4i %5i %4i %4i %4i %5i %6i %5i %6i %6i\n',[iitl,iimf,cw_opts(3:11)]);
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'For iitl=1, Enter Source Depths, Receiver Depths, Ranges:\n');
end
fprintf(fid_out,'*(5) nzs zs1 zs2 (m) ... nzr zr1 zr2 (m) ... nr r1 r2 (km) ...\n');
if iicw==1 | iiparm==1,
	orca_lim_out(fid_out,zs_lims,'zs_lims','%6.1f');
	orca_lim_out(fid_out,zr,'zr_lims','%6.1f');
	orca_lim_out(fid_out,rng_lims,'rng_lims','%6.1f');
end
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'For iimf>0 or iisig=1, enter Re/Im(0-3), Mag/Phase(0-3) Options and Depths:\n');
end
fprintf(fid_out,'*(6) iir/i iim/p  nzm zm1 zm2 ...\n');
if iimf,
    if cw_opts(14), mf_form=[0 1]; else, mf_form=[1 0]; end               % |phi| or Re(phi);
    if cw_opts(15), mf_form=3*mf_form; end                  % Output Im(phi) or arg(phi) also;
	fprintf(fid_out,'%10i %5i\n',mf_form);
	orca_lim_out(fid_out,zmf_lims,'zmf_lims','%8.3f');
end
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'BB MODE COMPUTATION PARAMETERS (iicw=2 on Line 1):\n');
	fprintf(fid_out,'fs      = Sample f;\n');
	fprintf(fid_out,'nfft/Tw = pos=NFFT (power of 2); neg=Time Window in s;\n');
	fprintf(fid_out,'iifft   = Output FFT File (0=no;1=zs,zr,r on Line 8; 2=read file on Line 10);\n');
	fprintf(fid_out,'iiout   = Output BB Eigenvalues and Functions (same options as iifft above);\n');
	fprintf(fid_out,'iift    = Freq Traj(ASCII);\n');
	fprintf(fid_out,'iimt    = Mode Traj(ASCII);\n');
	fprintf(fid_out,'iidc    = Disp Curves (0=no,1=vg,2=vph,3=both);\n');
	fprintf(fid_out,'iimf    = Mode Functions at Rec Depth on Line 8 (0=no,1=2D HDF,2=3D HDF);\n');
end
fprintf(fid_out,'*(7) fs  nfft/Tw  fmin  fmax iifft iiout iift iimt iidc iimf\n');
if iicw==2,
	if length(bb_parms)~=4, error('USER ERROR: bb_parms must be [fs,nfft/Tw,fmin,fmax].'); end
	if length(bb_opts)~=6, error('USER ERROR: bb_parms must be [iifft,iiout,iift,iimt,iidc,iimf].'); end
	fprintf(fid_out,'%7.1f %8.1f %5.0f %5.0f ',bb_parms);
	fprintf(fid_out,'%5i %5i %4i %4i %4i %4i \n',bb_opts);
end
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'For iifft=1, iiout=1, or iimf>0, enter src depths, rec depths, ranges:\n');
end
fprintf(fid_out,'*(8) nzs zs1 zs2 (m) ... nzr zr1 zr2 (m) ... nr r1 r2 (km) ...\n');
if iicw==2 & (iifft==1 | any(bb_opts([2,6])>0)),
	orca_lim_out(fid_out,zs_lims,'zs_lims','%8.3f');
	orca_lim_out(fid_out,zr,'zr_lims','%8.3f');
	orca_lim_out(fid_out,rng_lims,'rng_lims','%9.4f');
end
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'PARAMETER STUDY (iiparm=1 on Line 1):\n');
	fprintf(fid_out,'nrun  = # of CW mode runs;\n');
	fprintf(fid_out,'nparm = # of parameters to vary;\n');
	fprintf(fid_out,'rseed = Random # seed (integer) [0=none (vary linearly from val1 to val2)];\n');
	fprintf(fid_out,'obt   = Medium (0=ocean, 1=bottom layers, 2=top layers);\n');
	fprintf(fid_out,'nlay  = Layer #;\n');
	fprintf(fid_out,'ktb   = Bottom/Top of Layer (1=top, 2=bottom, neg=maintain gradient);\n');
	fprintf(fid_out,'pc    = Parm Code (0=h, 1=cp, 2=cs, 3=rho, 4=kp, 5=ks);\n');
	fprintf(fid_out,'val1,val2 = First, Last Values of Parameter;\n');
end
fprintf(fid_out,'*(9) nrun nparm  rseed [(obt nlay ktb pc val1,val2),j=1,nparm]\n');
if iiparm,
	if length(var_parm1)~=2, disp(var_parm1), error('USER ERROR: var_parm1 must be [nrun,nparm]'); end
	fprintf(fid_out,'%9i %5i      0\n',var_parm1)
	nparm=var_parm1(2); [nr,nc]=size(var_parm2);
	if nr~=nparm | nc~=6, error('USER ERROR: var_parm2 must be nparm by 6'); end
	for jparm=1:nparm,
		fprintf(fid_out,'%28i %4i %3i %2i %0.3f,%0.3f\n',var_parm2(jparm,:))
	end
end
%%fclose(fid_out); error('stopping');
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'S/R GEOM FOR SRC TRACK AND REC ARRAY (iitl=2 on Line 4 or iifft=2 on Line 8)\n');
end
fprintf(fid_out,'*(10) zs  n_src_seg  ''array_geom_file_name''\n');
if (iicw==1 & cw_opts(1)==2) | (iicw==2 & iifft==2),
% 	disp('Track parameters being implemented');
	fprintf(fid_out,'%8.3f          %1i  ''%s''\n',zs_lims(1),1,zr_lims)
end
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'Source Track: v~m/s; t,dt~min; cpa,x,y~km; phi~deg E of N (see manual)\n');
	fprintf(fid_out,'      1 iic    v     t1     t2 +dt/-nt   cpa   phi              (POLAR FORM)\n');
end
fprintf(fid_out,'*(11) 2 iic    v     t1     t2 +dt/-nt    x1,y1    x2,y2    (X-Y FORM)\n');
if (iicw==1 & cw_opts(1)==2) | (iicw==2 & iifft==2),
% 	disp('Track parameters not implemented');
    rng=adi_lim_eval(rng_lims); nrng=length(rng);
	fprintf(fid_out,'      2   1    0      0      1     %i %7.3f,0  %7.3f,0\n',-nrng,rng(1),rng(end))
end
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'==> k-PLANE IMAGES (iikpl>0 on Line 1)\n');
	fprintf(fid_out,'iivar = Variable to Image [1=R1*R2, 2=d(R1*R2)/dk, 3=d(R1*R2)/dw];\n');
	fprintf(fid_out,'iikf  = Form for kr,ki (1=k/kmin, 2=k, 3=kr~kr/kmin,ki~dB/km);\n');
	fprintf(fid_out,'kduc  = Duct Number for Reference Depth (0 for min cp in ocean);\n');
	fprintf(fid_out,'iiph  = Phase Wrap (1=-180,180; 2=0,360);\n');
	fprintf(fid_out,'iishp,iishs = Riemann Sheet for p/s Branch Cuts (+1 or -1);\n');
end
fprintf(fid_out,'*(12) freq iivar iikf   kr1   kr2  nkr   ki1   ki2  nki nduct iiph iishp iishs\n');
if iikpl~=0,
	if length(kpl_parms)~=13, error('USER ERROR: kpl_parms must have length 13.'); end
	fprintf(fid_out,'%10.3f %5i %4i %5.2f %5.2f %4i %5.1f %5.1f %4i %5i %4i %5i %5i\n',kpl_parms)
%       100     1    3   0.8   1.0  101   200     0  101     1    2     1     1
end
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'==> REFLECTION COEFFICIENT VS f (Hz) AND GRAZING ANGLE (deg)\n');
	fprintf(fid_out,'R vs Frequency and Angle (iirc=1 on Line 1):\n');
end
%fprintf(fid_out,'*(13) freq1  freq2  nfreq  iilog  theta1  theta2  ntheta\n');
fprintf(fid_out,'*(13) nfreq,freq1,freq2...  ntheta,theta1,theta2 ...\n');
if iirc==1,
	if ~iscell(rc_parms) | length(rc_parms)~=2, 
        disp(rc_parms),
        error('USER ERROR: reflection coeff parms must be 2-element cell array.'); 
    end
    orca_lim_out(fid_out,rc_parms{1},'freq_rc_lims','%6.1f');
    orca_lim_out(fid_out,rc_parms{2},'freq_theta_lims','%6.1f');
end
%
if iicomm,
	fprintf(fid_out,'--------------------------------------------------------------------------\n');
	fprintf(fid_out,'FFT File of R vs. Frequency and Angle (iirc=2 on Line 1):\n');
end
fprintf(fid_out,'*(14) freq1  freq2     fs  nfft  theta1  theta2  ntheta\n');
if iirc==2,
	error('iirc=2 for FFT file not supported now.');
end
%
fclose(fid_out);
disp(['Created OPT file ',opt_file,'.']);
%%%
%
function orca_lim_out(fid_out,f_lims,var_str,fmt);
%
%disp(f_lims), disp(var_str), disp(size(f_lims)),
[nr,nc]=size(f_lims); err=0;
if nr==1 & nc>1,
	if nc~=3, 
        err=1;
    else
		nfreq=f_lims(3); f1=f_lims(1); 
		if nfreq>0,
			if round(nfreq)~=nfreq, err=2; else, f2=f_lims(2); end
		else
			df=-nfreq; freq=[f1:df:f_lims(2)]; f2=freq(length(freq)); nfreq=length(freq);
		end
		fprintf(fid_out,['%5i ',fmt,' ',fmt,'\n'],[-nfreq,f1,f2]);
    end
elseif nc==1,
	nfreq=nr;
	fprintf(fid_out,'%6i ',nfreq);
	fprintf(fid_out,[fmt,' ',fmt,' ',fmt,' ',fmt,' ',fmt,' ',fmt,'\n'],f_lims(1:nfreq));		% 5 entries per line;
	fprintf(fid_out,'\n');
else
	err=1;
end
%
if err==1, 
	disp(f_lims);
	error(['USER ERROR: ',var_str,' must be in form [zmin,zmax,nz], [zmin,zmax,-dz], or [z1;z2;...zn]']);
elseif err==2,
	disp(f_lims);
	error(['USER ERROR: for ',var_str,' in form [zmin,zmax,nz], nz must be integer.']);	
end
%
function f_lims_out=orca_lims(f_lims)
%
[nr,nc]=size(f_lims);
if nr==1,
	if f_lims(3)<0,
        df=-f_lims(3); freq=[f_lims(1):df:f_lims(2)];
        f_lims_out=[f_lims(1),freq(end),length(freq)];
	else
        f_lims_out=f_lims;
	end
elseif nc==1,
    f_lims_out=[length(f_lims), f_lims'];
else
    disp(f_lims); error('Illegal limits spec: ');
end
