#!/usr/bin/octave -q

page_screen_output(0);
page_output_immediately(1);

d0 = 790.0;
r0 = d0/2;

rrange = [r0-5:r0+5];
cenrange = 100;

inpath= "/media/Shiva_D/Astro_Imaging/Canon450D/SolarSystem/SoFi_20141023/png2octave/";
outpath= "/home/gottsch/sofi_20141022/octave2reg/";
fileList = glob([inpath,"*.png"]) ;

for i = 1:length(fileList)
  file= fileList{i};
  [path,fname,ext] = fileparts(file);
  file_edg= [ fname , "_edge.png"];
  file_ct=  [ fname , "_cent.png"];

  printf ("Working on : %s\n", file);
  img = imread(file);

  % Apply edge detection to 1 color channel only
  img_edge = edge(img, 'Canny', [50,4]);
  imwrite((img_edge), [outpath,file_edg] );
  printf ("Edge detected and written : %s\n",file_edg);

  printf ("Hough circle detection started : %s\n",strftime ("%Y-%m-%d %H:%M:%S", localtime (time ())));
  h = hough_circle(img_edge, rrange);
  printf ("Hough circle detection finished : %s\n",strftime ("%Y-%m-%d %H:%M:%S", localtime (time ())));

  [peak, idx]= max(h(:))
  [ypeak, xpeak, z]= ind2sub(size(h),idx);

  % now find the centroid of the region around (xpeak, ypeak) in the Hough tranform
  roi = h((ypeak-cenrange:ypeak+cenrange), (xpeak-2*cenrange:xpeak+2*cenrange), z);

  % focus on prominent features in the Hough transform
  roi = roi.**2; 
  roi = roi/sum(roi(:));
  %surf(roi); drawnow();

  % redefine xpeak, ypeak as centroids of the region of interest
  centroids = regionprops(true(size(roi)), roi, 'WeightedCentroid').WeightedCentroid ;
  xpeak2 = centroids(1) - 2*cenrange + (xpeak-1);
  ypeak2 = centroids(2) - cenrange + (ypeak-1);
  printf ("Found center X= %8.2f  Y= %8.2f \n",xpeak2,ypeak2);

  % shift to image center
  [h,w]= size(img);
  target_pos_x = w/2;
  target_pos_y = h/2;
  shift_x= xpeak2-target_pos_x;
  shift_y= ypeak2-target_pos_y;
  printf ("Shift image X : %4d -> %4d. Y : %4d -> %4d\n",xpeak2,target_pos_x,ypeak2,target_pos_y);
  imgc = uint8(imtranslate(img, -round(shift_x), round(shift_y)));

  imwrite(imgc, [outpath,file_ct] );
  printf ("Image saved to : %s\n",file_ct);
  printf ("Done with Image : %s\n",strftime ("%Y-%m-%d %H:%M:%S", localtime (time ())));
  
end
