#!/bin/csh


echo "#################################################################"
echo "Convert surfaces to matlab/brainstorm files."
echo "#################################################################"

cd  ${SUBJECTS_DIR}/${subject}/MODEL

##########must be changed if you want to work with different subcortical volumes##########
rename 17 l_hipp 17.ply
rename 18 l_amy 18.ply
rename 53 r_hipp 53.ply
rename 54 r_amy 54.ply

rm -f ${SCRIPTS_DIR}/${subject}.lock

foreach model (l_hipp l_amy r_hipp r_amy)
	if (-e l_hipp.1D.topo) then
		set allsurfs="${allsurfs}', '${model}"
	else
		set allsurfs="surfarray = {'${model}"
	endif
	ConvertSurface -i ${model}.ply -o_1D ${model}.1D.coord ${model}.1D.topo
end
##########must be changed if you want to work with different subcortical volumes##########





##########must be changed if you want to work with different freesurfer surfaces##########
foreach surf (lh.pial rh.pial lh.outer_skin_surface lh.outer_skull_surface)
	mris_convert ${surf} ${surf}.asc
	ConvertSurface -i ${surf}.asc -o_1D ${surf}.1D.coord ${surf}.1D.topo
	set allsurfs="${allsurfs}', '${surf}"
end
##########must be changed if you want to work with different freesurfer surfaces##########

set allsurfs="${allsurfs}'}"

echo "function importsurface" > ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "cd  ${SUBJECTS_DIR}/${subject}/MODEL;" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "${allsurfs};" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "for i = 1:length(surfarray);" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "    surface = surfarray{i};" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "    fprintf(surface);" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "coord = '.1D.coord';" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "topo = '.1D.topo';" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "Vertices = importdata(strcat(surface, coord)) / 1000;" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "Faces = importdata(strcat(surface, topo)) + 1;" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "Comment = surface;" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "tessfile = strcat('tess_', surface, '.mat');" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "save(tessfile, 'Faces', 'Vertices', 'Comment');" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
echo "end" >> ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m

chmod a+rwx ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m
matlab -nodesktop -nosplash -nodisplay -r "run ${SUBJECTS_DIR}/${subject}/MODEL/importsurface.m ; quit;"
cp *.mat ${BRAINSTORM_DIR}/${subject}
cp ${SUBJECTS_DIR}/${subject}/mri/T1.mgz ${BRAINSTORM_DIR}/${subject}

