/* 必要なヘッダー */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <math.h>

/* SOCKET経由でVMEのモーターとカウンタを使うためのヘッダー */
#include "api_vmecounter.h"
#include "api_vmepmc.h"
#include "api_sock.h"


void main(int argc, char *argv[])
{
int i, k, th_ch, cntr_ch;
long count[8], c_max, th_peak, th_span, th_org;
long th_now, th_start, th_back, th_step, th_stop, th_n;
float time;
FILE *fp;

/* 引数の数をチェックする。数が合わなければ、使用方法を表示して終了。 */
if(argc != 7) {
printf("Usage : peak_rel_search [th_ch] [th_span] [th_step] [th_backlash] [counter ch] [file]\n");
printf(" counter ch : 0-7\n");
exit(0);
}

/* 引数の解釈 */
time=1.0; /* 測定時間は1秒に固定する。 */
th_ch=atoi(argv[1]); /* チャンネルの読み込み */
th_span=atol(argv[2]); /* 測定範囲 */
th_step=atol(argv[3]); /* ステップ */
th_back=atol(argv[4]); /* バックラッシュ */
cntr_ch=atoi(argv[5]); /* 強度をモニターする検出器のチャンネル */
if((fp=fopen(argv[6], "w")) == NULL) { /* ファイルのopen。失敗したら終了。 */
printf("cannot open file %s\n", argv[6]);
exit(0);
}

/* WSへの接続 */
api_sock_open();

/* モーターの現在値の読み出し。APIのマニュアル参照。 */
api_vmepmc_read_position(API_VMEPMC_ST1, th_ch, &th_org);
printf("initial pulse : ch%d %ld(pls)\n", th_ch, th_org);

/* 測定点数、測定開始点と終了点の計算。 */
th_n=th_span/th_step+1;
th_start=th_org-(long)th_span/2.0;
th_stop=th_org+(long)th_span/2.0;

/* バックラッシュをとる。 */
th_now=th_start;
printf("remove backlash : ch%d %ld(pls)\n", th_ch, th_now-th_back);
api_vmepmc_write_position(API_VMEPMC_ST1, th_ch, th_now-th_back);
/* 1秒待つ。 */
sleep(1);

/* スキャン開始 */
c_max=0;
for(i=0; i<th_n; i++) {
/* モーター移動。APIのマニュアル参照。 */
api_vmepmc_write_position(API_VMEPMC_ST1, th_ch, th_now);
/* 移動後のモーターの現在値の読み出し。APIのマニュアル参照。 */
api_vmepmc_read_position(API_VMEPMC_ST1, th_ch, &th_now);

  /* 1秒間測定。APIのマニュアル参照。 */
api_vmecounter_read_count(API_VMECOUNTER_ST1, 1, time, count);

/* ファイルとスクリーンに書き出す。 */
fprintf(fp, "%ld ", th_now);
printf("ch%d %ld(pls) ", th_ch, th_now);
for (k=0; k<8; k++) {
fprintf(fp, "%ld ", count[k]);
printf("%ld ", count[k]);
}
fprintf(fp, "\n");
printf("\n");

/* 最大値とそれを与えるモーターのパルスを探す。 */
if (count[cntr_ch] > c_max) {
c_max=count[cntr_ch];
th_peak=th_now;
}

/* 次へ。 */
th_now=th_now+th_step;
}

/* 測定された最大値に移動する。 */
printf("go to peak pulse : ch%d %ld(pls)\n", th_ch, th_peak);
api_vmepmc_write_position(API_VMEPMC_ST1, th_ch, th_peak-th_back);
sleep(1);
api_vmepmc_write_position(API_VMEPMC_ST1, th_ch, th_peak);

/* 念のため最大値をもう一度測定する。 */
fprintf(fp, "%ld ", th_peak);
printf("ch%d %ld(pls) ", th_ch, th_peak);
api_vmecounter_read_count(API_VMECOUNTER_ST1, 1, time, count);
for (k=0; k<8; k++) {
fprintf(fp, "%ld ", count[k]);
printf("%ld ", count[k]);
}
fprintf(fp, "\n");
printf("\n");

/* ファイルを閉じて、WSへの接続を切る。 */
fclose(fp);
api_sock_close();
}

BACK